<template>
  <div class="bigbox">
    <div class="topbox">
      <el-form
        :model="form"
        ref="form"
        label-position="left"
        label-width="80px"
        onsubmit="return false"
      >
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="用电企业">
              <FilterSelect2
                v-model="form.orgNo"
                :optionlist="companyList"
                :valuekey="{ name: 'bizOrgName', value: 'bizOrgNo' }"
                placeholder="请选择用电企业"
                :clearable="false"
                @changeSelect="companyChange"
              ></FilterSelect2>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="年月">
              <el-date-picker
                v-model="dateRange"
                type="monthrange"
                style="width: 100%"
                size="small"
                :clearable="false"
                range-separator="-"
                start-placeholder="开始月份"
                end-placeholder="结束月份"
                format="yyyy-MM"
                value-format="yyyy-MM"
                @change="dateRangeChange"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12" style="text-align: right">
            <el-form-item>
              <Twobtn @chaxun="chaxun" @chongzhi="chongzhi"></Twobtn>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="bodybox">
      <div class="titlebox">
        <div class="text">运维报告</div>
        <TopTile
          @command="command"
          @daochu="daochu"
          @shuaxin="shuaxin"
        ></TopTile>
      </div>
      <div class="table-content">
        <template>
          <el-table
            v-loading="loading"
            :data="tableData"
            style="width: 100%"
            border
            id="exportTabyong"
            ref="table"
            :size="iissize"
            :header-cell-style="{
              background: '#f5f5f5',
              'text-align': 'center'
            }"
          >
            <template slot="empty">
              <el-empty description="暂无数据"></el-empty>
            </template>
            <el-table-column
              type="index"
              align="center"
              label="序号"
              width="100"
            >
            </el-table-column>
            <el-table-column prop="orgName" label="用电企业"> </el-table-column>
            <el-table-column
              prop="month"
              label="年月"
              min-width="100"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="isGenerate"
              label="是否生成"
              min-width="80"
              align="center"
            >
              <template slot-scope="scope">
                <el-tag :type="scope.row.isGenerate ? 'success' : 'danger'">
                  {{ scope.row.isGenerate ? '是' : '否' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column
              prop="generateDate"
              label="生成日期"
              min-width="100"
              align="center"
            >
              <template slot-scope="scope">
                {{ scope.row.generateDate || '-' }}
              </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" width="200">
              <template slot-scope="scope">
                <div class="operate">
                  <!-- 未生成时显示生成图标 -->
                  <el-tooltip
                    v-if="!scope.row.isGenerate"
                    class="item"
                    effect="dark"
                    content="生成"
                    placement="top"
                  >
                    <i
                      style="
                        font-size: 14px;
                        color: rgb(64, 149, 229);
                        cursor: pointer;
                      "
                      class="el-icon-document-add"
                      @click="generateReport(scope.row)"
                    ></i>
                  </el-tooltip>

                  <!-- 已生成时显示浏览和删除图标 -->
                  <template v-if="scope.row.isGenerate">
                    <el-tooltip
                      class="item"
                      effect="dark"
                      content="浏览"
                      placement="top"
                    >
                      <i
                        style="
                          font-size: 14px;
                          color: rgb(64, 149, 229);
                          cursor: pointer;
                        "
                        class="el-icon-view"
                        @click="openReportDialog(scope.row, 'view')"
                      ></i>
                    </el-tooltip>

                    <el-popconfirm
                      title="是否删除已生成数据？"
                      confirm-button-text="确定"
                      cancel-button-text="取消"
                      icon="el-icon-info"
                      icon-color="red"
                      @confirm="handleDel(scope.row)"
                    >
                      <el-tooltip
                        slot="reference"
                        class="item"
                        effect="dark"
                        content="删除"
                        placement="top"
                      >
                        <i
                          style="font-size: 14px; color: red; cursor: pointer"
                          class="el-icon-delete"
                        ></i>
                      </el-tooltip>
                    </el-popconfirm>
                  </template>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </template>
        <div class="fenye">
          <el-pagination
            background
            layout="prev, pager, next"
            :current-page.sync="pageobj._pageNo"
            @current-change="currentChange"
            :total="total"
          >
          </el-pagination>
        </div>
      </div>
    </div>

    <!-- 生成/浏览报告对话框 -->
    <el-dialog
      :visible.sync="generateDialogVisible"
      width="85%"
      :close-on-click-modal="false"
      top="2vh"
      :before-close="closeDialog"
    >
      <div style="padding: 20px; min-height: 600px">
        <!-- 下载按钮区域 -->
        <div style="text-align: right">
          <el-button
            type="primary"
            size="small"
            icon="el-icon-download"
            :loading="downloadLoading"
            @click="downloadReport"
          >
            下载报告
          </el-button>
        </div>
        <!-- 报告内容区域 -->
        <div class="report-content">
          <h3 style="text-align: center; margin-bottom: 10px">
            {{ reportData ? reportData.orgName : currentRow.orgName }}
            用电及配电运行分析报告
          </h3>
          <p style="text-align: center; margin-bottom: 30px; color: #666">
            时间：{{ reportData ? reportData.month : currentRow.month }}
          </p>

          <div
            style="
              text-align: justify;
              line-height: 1.8;
              margin-bottom: 30px;
              padding: 20px;
              background: #f9f9f9;
              border-radius: 4px;
            "
          >
            <p>
              随着电力行业信息化的迅速发展，电力运维涉及的信息系统越来越多，为了保证电力系统的安全运行。了解电力系统运行状况，需要对电力系统的各种运行参数进行实时的检测，电力监控系统成功的、高效的完成了这项任务，电力监控系统已经成为电力系统能够自动化重要组成部分，成为保证电力系统安全运行的重要措施之一。电力监控系统是利用计算机、计量保护装置和总线技术，对高、低压配电系统的实时数据、开关状态及远程控制进行了集中管理，该电力监控系统可以为企业提供"监控一体化"的整体解决方案。"监、控、管"一体化解决方案。
            </p>
          </div>

          <div style="margin-bottom: 20px">
            <div
              style="font-weight: bold; margin-bottom: 15px; font-size: 16px"
            >
              一、项目概况
            </div>

            <!-- 项目概况表格 -->
            <div style="margin-bottom: 20px">
              <table class="project-overview-table" v-if="reportData">
                <tr>
                  <td class="table-label">项目名称</td>
                  <td class="table-value">{{ reportData.orgName || '-' }}</td>
                  <td class="table-label">报告日期</td>
                  <td class="table-value">{{ reportData.month || '-' }}</td>
                </tr>
                <tr>
                  <td class="table-label">电站总容量</td>
                  <td class="table-value">
                    {{ reportData.stationCapacity || '-' }} (kVA)
                  </td>
                  <td class="table-label">电压等级</td>
                  <td class="table-value">
                    {{ reportData.voltageLevel || '-' }}
                  </td>
                </tr>
                <tr>
                  <td class="table-label">监控点数量</td>
                  <td class="table-value">
                    {{ reportData.monitorPointNum || '-' }}
                  </td>
                  <td class="table-label">变压器数量</td>
                  <td class="table-value">
                    {{ reportData.transformerNum || '-' }}台
                  </td>
                </tr>
                <tr>
                  <td class="table-label">电价方案</td>
                  <td class="table-value">
                    {{ reportData.electricityPriceScheme || '-' }}
                  </td>
                  <td class="table-empty"></td>
                  <td class="table-empty"></td>
                </tr>
              </table>
            </div>

            <!-- 变压器信息 -->
            <div
              style="margin-top: 20px"
              v-if="reportData && reportData.transformerList"
            >
              <h4
                style="margin-bottom: 10px; font-weight: bold; text-align: left"
              >
                变压器信息
              </h4>
              <table class="transformer-info-table">
                <tr>
                  <td class="table-header">变压器名称</td>
                  <td class="table-header">变压器容量(kVA)</td>
                  <td class="table-header">运行状态</td>
                </tr>
                <tr
                  v-for="(transformer, index) in reportData.transformerList"
                  :key="index"
                >
                  <td class="table-data">{{ transformer.name || '-' }}</td>
                  <td class="table-data">{{ transformer.capacity || '-' }}</td>
                  <td class="table-data">
                    <span class="status-tag">{{
                      transformer.status || '-'
                    }}</span>
                  </td>
                </tr>
                <tr v-if="reportData.transformerList.length === 0">
                  <td class="table-note" colspan="3">暂无变压器信息</td>
                </tr>
              </table>
            </div>
          </div>

          <!-- 二、用电基本情况 -->
          <div style="margin-top: 30px">
            <div
              style="font-weight: bold; margin-bottom: 15px; font-size: 16px"
            >
              二、用电基本情况
            </div>

            <table class="electricity-basic-table" v-if="reportData">
              <thead>
                <tr>
                  <th class="table-header">序号</th>
                  <th class="table-header">监测类</th>
                  <th class="table-header">监测项</th>
                  <th class="table-header">监测标准</th>
                  <th class="table-header">得分</th>
                  <th class="table-header">评价</th>
                </tr>
              </thead>
              <tbody>
                <tr
                  v-for="(item, index) in electricityBasicDataList"
                  :key="index"
                >
                  <td class="table-data">{{ item.序号 }}</td>
                  <td
                    class="table-data"
                    v-if="item.监测类RowSpan > 0"
                    :rowspan="item.监测类RowSpan"
                  >
                    {{ item.监测类 }}
                  </td>
                  <td class="table-data">{{ item.监测项 }}</td>
                  <td class="table-data">{{ item.监测标准 }}</td>
                  <td class="table-data">{{ item.得分 }}</td>
                  <td class="table-data">{{ item.评价 }}</td>
                </tr>
              </tbody>
            </table>
          </div>

          <!-- 三、电量电费分析 -->
          <div style="margin-top: 30px">
            <div
              style="font-weight: bold; margin-bottom: 15px; font-size: 16px"
            >
              三、电量电费分析
            </div>

            <!-- 3.1电量电费概况 -->
            <div style="margin-bottom: 20px">
              <div
                style="font-weight: bold; margin-bottom: 10px; font-size: 14px"
              >
                3.1电量电费概况
              </div>

              <div
                style="
                  text-align: justify;
                  line-height: 1.8;
                  margin-bottom: 20px;
                  padding: 15px;
                  background: #f9f9f9;
                  border-radius: 4px;
                  font-size: 14px;
                "
              >
                <p>
                  本月贵单位总用电量为{{
                    formatNumber(electricityViewData.thisMonthTotalElectricity)
                  }}kWh,上月用电量为{{
                    formatNumber(electricityViewData.lastMonthTotalElectricity)
                  }}kWh,同比{{
                    formatNumber(
                      electricityViewData.thisMonthElectricityCompare
                    )
                  }}kWh,其中:尖时段用电量{{
                    formatNumber(electricityViewData.thisMonthSharpElectricity)
                  }}kWh,峰时段用电量{{
                    formatNumber(electricityViewData.thisMonthPeakElectricity)
                  }}kWh,平时段用电量{{
                    formatNumber(electricityViewData.thisMonthFlatElectricity)
                  }}kWh,谷时段用电量{{
                    formatNumber(
                      electricityViewData.thisMonthValleyElectricity
                    )
                  }}kWh。详情如下表所示:
                </p>
              </div>

              <!-- 电量电费详细表格 -->
              <div class="table-container">
                <table class="electricity-cost-table">
                  <thead>
                    <tr>
                      <th class="table-header" rowspan="2">统计月份</th>
                      <th class="table-header" rowspan="2">计量点名称</th>
                      <th class="table-header" colspan="3">尖时段</th>
                      <th class="table-header" colspan="3">峰时段</th>
                      <th class="table-header" colspan="3">平时段</th>
                      <th class="table-header" colspan="3">谷时段</th>
                      <th class="table-header" colspan="3">总计</th>
                    </tr>
                    <tr>
                      <th class="table-header">电量(kwh)</th>
                      <th class="table-header">单价(元/kwh)</th>
                      <th class="table-header">电费(元)</th>
                      <th class="table-header">电量(kwh)</th>
                      <th class="table-header">单价(元/kwh)</th>
                      <th class="table-header">电费(元)</th>
                      <th class="table-header">电量(kwh)</th>
                      <th class="table-header">单价(元/kwh)</th>
                      <th class="table-header">电费(元)</th>
                      <th class="table-header">电量(kwh)</th>
                      <th class="table-header">单价(元/kwh)</th>
                      <th class="table-header">电费(元)</th>
                      <th class="table-header">电量(kwh)</th>
                      <th class="table-header">单价(元/kwh)</th>
                      <th class="table-header">电费(元)</th>
                    </tr>
                  </thead>
                  <tbody>
                    <!-- 本月数据 -->
                    <tr>
                      <td class="table-data">本月</td>
                      <td class="table-data" style="text-align: center">
                        {{ electricityViewData.meterPointName || '-' }}
                      </td>
                      <!-- 尖时段 -->
                      <td class="table-data">
                        {{
                          formatNumber(
                            electricityViewData.thisMonthSharpElectricity
                          )
                        }}
                      </td>
                      <td class="table-data">
                        {{
                          formatNumber(
                            electricityViewData.thisMonthSharpUnitPrice
                          )
                        }}
                      </td>
                      <td class="table-data">
                        {{
                          formatNumber(
                            electricityViewData.thisMonthSharpElectricityFee
                          )
                        }}
                      </td>
                      <!-- 峰时段 -->
                      <td class="table-data">
                        {{
                          formatNumber(
                            electricityViewData.thisMonthPeakElectricity
                          )
                        }}
                      </td>
                      <td class="table-data">
                        {{
                          formatNumber(
                            electricityViewData.thisMonthPeakUnitPrice
                          )
                        }}
                      </td>
                      <td class="table-data">
                        {{
                          formatNumber(
                            electricityViewData.thisMonthPeakElectricityFee
                          )
                        }}
                      </td>
                      <!-- 平时段 -->
                      <td class="table-data">
                        {{
                          formatNumber(
                            electricityViewData.thisMonthFlatElectricity
                          )
                        }}
                      </td>
                      <td class="table-data">
                        {{
                          formatNumber(
                            electricityViewData.thisMonthFlatUnitPrice
                          )
                        }}
                      </td>
                      <td class="table-data">
                        {{
                          formatNumber(
                            electricityViewData.thisMonthFlatElectricityFee
                          )
                        }}
                      </td>
                      <!-- 谷时段 -->
                      <td class="table-data">
                        {{
                          formatNumber(
                            electricityViewData.thisMonthValleyElectricity
                          )
                        }}
                      </td>
                      <td class="table-data">
                        {{
                          formatNumber(
                            electricityViewData.thisMonthValleyUnitPrice
                          )
                        }}
                      </td>
                      <td class="table-data">
                        {{
                          formatNumber(
                            electricityViewData.thisMonthValleyElectricityFee
                          )
                        }}
                      </td>
                      <!-- 总计 -->
                      <td class="table-data">
                        {{
                          formatNumber(
                            electricityViewData.thisMonthTotalElectricity
                          )
                        }}
                      </td>
                      <td class="table-data">
                        {{
                          formatNumber(
                            electricityViewData.thisMonthElectricityPrice
                          )
                        }}
                      </td>
                      <td class="table-data">
                        {{
                          formatNumber(
                            electricityViewData.thisMonthTotalElectricityFee
                          )
                        }}
                      </td>
                    </tr>
                    <!-- 上月数据 -->
                    <tr>
                      <td class="table-data">上月</td>
                      <td class="table-data" style="text-align: center">
                        {{
                          electricityViewData.meterPointName ||
                          '东区配电箱总进线'
                        }}
                      </td>
                      <!-- 尖时段 -->
                      <td class="table-data">
                        {{
                          formatNumber(
                            electricityViewData.lastMonthSharpElectricity
                          )
                        }}
                      </td>
                      <td class="table-data">
                        {{
                          formatNumber(
                            electricityViewData.lastMonthSharpUnitPrice
                          )
                        }}
                      </td>
                      <td class="table-data">
                        {{
                          formatNumber(
                            electricityViewData.lastMonthSharpElectricityFee
                          )
                        }}
                      </td>
                      <!-- 峰时段 -->
                      <td class="table-data">
                        {{
                          formatNumber(
                            electricityViewData.lastMonthPeakElectricity
                          )
                        }}
                      </td>
                      <td class="table-data">
                        {{
                          formatNumber(
                            electricityViewData.lastMonthPeakUnitPrice
                          )
                        }}
                      </td>
                      <td class="table-data">
                        {{
                          formatNumber(
                            electricityViewData.lastMonthPeakElectricityFee
                          )
                        }}
                      </td>
                      <!-- 平时段 -->
                      <td class="table-data">
                        {{
                          formatNumber(
                            electricityViewData.lastMonthFlatElectricity
                          )
                        }}
                      </td>
                      <td class="table-data">
                        {{
                          formatNumber(
                            electricityViewData.lastMonthFlatUnitPrice
                          )
                        }}
                      </td>
                      <td class="table-data">
                        {{
                          formatNumber(
                            electricityViewData.lastMonthFlatElectricityFee
                          )
                        }}
                      </td>
                      <!-- 谷时段 -->
                      <td class="table-data">
                        {{
                          formatNumber(
                            electricityViewData.lastMonthValleyElectricity
                          )
                        }}
                      </td>
                      <td class="table-data">
                        {{
                          formatNumber(
                            electricityViewData.lastMonthValleyUnitPrice
                          )
                        }}
                      </td>
                      <td class="table-data">
                        {{
                          formatNumber(
                            electricityViewData.lastMonthValleyElectricityFee
                          )
                        }}
                      </td>
                      <!-- 总计 -->
                      <td class="table-data">
                        {{
                          formatNumber(
                            electricityViewData.lastMonthTotalElectricity
                          )
                        }}
                      </td>
                      <td class="table-data">
                        {{
                          formatNumber(
                            electricityViewData.lastMonthElectricityPrice
                          )
                        }}
                      </td>
                      <td class="table-data">
                        {{
                          formatNumber(
                            electricityViewData.lastMonthTotalElectricityFee
                          )
                        }}
                      </td>
                    </tr>
                  </tbody>
                </table>
              </div>
            </div>
          </div>

          <!-- 3.2 负荷情况及基本电费 -->
          <div style="margin-top: 30px">
            <div
              style="font-weight: bold; margin-bottom: 15px; font-size: 16px"
            >
              3.2 负荷情况及基本电费
            </div>

            <div
              style="
                text-align: justify;
                line-height: 1.8;
                margin-bottom: 20px;
                padding: 15px;
                background: #f9f9f9;
                border-radius: 4px;
                font-size: 14px;
              "
            >
              <p>
                贵单位运行容量为{{
                  formatNumber(loadViewData.stationCapacity)
                }}kVA，本月最大需量值为{{
                  formatNumber(loadViewData.thisMonthMaxDemandValue)
                }}kW，最大需量/运行容量比值为{{
                  formatNumber(loadViewData.demandCapacityRatio)
                }}%。根据基本电费计算方法,贵司如选择按照容量计费方式,则基本电费为{{
                  formatNumber(loadViewData.basicElectricityFee)
                }}元;如选择按合同需量计费方式,则基本电费为{{
                  formatNumber(
                    loadViewData.basicElectricityFeeByContractDemand
                  )
                }}元;如选择按实际需量计费方式,则基本电费为{{
                  formatNumber(loadViewData.basicElectricityFeeByActualDemand)
                }}元。本月最大负荷为{{
                  formatNumber(loadViewData.thisMonthMaxLoad)
                }}kW(发生于{{
                  loadViewData.thisMonthMaxLoadTime || '-'
                }}),平均负荷为{{
                  formatNumber(loadViewData.thisMonthAvgLoad)
                }}kW,负荷率为{{
                  formatNumber(loadViewData.thisMonthLoadRate)
                }}%。
              </p>
            </div>

            <!-- 负荷特性分析表格 -->
            <div style="margin-bottom: 20px">
              <div
                style="
                  font-weight: bold;
                  margin-bottom: 10px;
                  font-size: 14px;
                  text-align: center;
                "
              >
                表1 本月负荷特性分析
              </div>
              <table class="load-analysis-table">
                <thead>
                  <tr>
                    <th class="table-header">统计月份</th>
                    <th class="table-header">计量点名称</th>
                    <th class="table-header">最高负荷(kW)</th>
                    <th class="table-header">最低负荷(kW)</th>
                    <th class="table-header">平均负荷(kW)</th>
                    <th class="table-header">负荷率(%)</th>
                  </tr>
                </thead>
                <tbody>
                  <!-- 本月数据 -->
                  <tr>
                    <td class="table-data">本月</td>
                    <td class="table-data" style="text-align: center">
                      {{ loadViewData.meterPointName || '东区配电箱总进线' }}
                    </td>
                    <td class="table-data">
                      {{ formatNumber(loadViewData.thisMonthMaxLoad) }}
                    </td>
                    <td class="table-data">
                      {{ formatNumber(loadViewData.thisMonthMinLoad) }}
                    </td>
                    <td class="table-data">
                      {{ formatNumber(loadViewData.thisMonthAvgLoad) }}
                    </td>
                    <td class="table-data">
                      {{ formatNumber(loadViewData.thisMonthLoadRate) }}
                    </td>
                  </tr>
                  <!-- 上月数据 -->
                  <tr>
                    <td class="table-data">上月</td>
                    <td class="table-data" style="text-align: center">
                      {{ loadViewData.meterPointName || '东区配电箱总进线' }}
                    </td>
                    <td class="table-data">
                      {{ formatNumber(loadViewData.lastMonthMaxLoad) }}
                    </td>
                    <td class="table-data">
                      {{ formatNumber(loadViewData.lastMonthMinLoad) }}
                    </td>
                    <td class="table-data">
                      {{ formatNumber(loadViewData.lastMonthAvgLoad) }}
                    </td>
                    <td class="table-data">
                      {{ formatNumber(loadViewData.lastMonthLoadRate) }}
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>

            <!-- 图表区域 -->
            <div style="margin-top: 20px">
              <div
                style="
                  font-weight: bold;
                  margin-bottom: 10px;
                  font-size: 14px;
                  text-align: center;
                "
              >
                图1 本月负荷特性曲线
              </div>
              <div style="height: 300px; padding: 10px">
                <nt-echart
                  id="load-chart"
                  :loading="loading"
                  :options="loadCurveOptions"
                ></nt-echart>
              </div>
            </div>

            <div style="margin-top: 20px">
              <div
                style="
                  font-weight: bold;
                  margin-bottom: 10px;
                  font-size: 14px;
                  text-align: center;
                "
              >
                图2 典型日负荷曲线 ({{ loadViewData.thisMonthMaxLoadTime }})
              </div>
              <div style="height: 300px; padding: 10px">
                <nt-echart
                  id="typical-day-load-chart"
                  :loading="loading"
                  :options="typicalDayLoadCurveOptions"
                ></nt-echart>
              </div>
            </div>
          </div>

          <!-- 3.3 电价分析 -->
          <div style="margin-top: 30px">
            <div
              style="font-weight: bold; margin-bottom: 15px; font-size: 16px"
            >
              3.3 电价分析
            </div>

            <!-- 电价分析图表 -->
            <div style="margin-top: 20px">
              <div style="height: 300px; padding: 10px">
                <nt-echart
                  id="price-analysis-chart"
                  :loading="loading"
                  :options="electricityPriceOptions"
                ></nt-echart>
              </div>
            </div>

            <!-- 3.4 企业总用电量 -->
            <div style="margin-top: 30px">
              <div
                style="font-weight: bold; margin-bottom: 15px; font-size: 16px"
              >
                3.4 企业总用电量
              </div>

              <div
                style="
                  display: flex;
                  justify-content: space-between;
                  align-items: flex-start;
                  margin-bottom: 20px;
                  flex-wrap: wrap;
                "
              >
                <!-- Left side: 2x2 grid of cards -->
                <div class="power-cards-grid">
                  <div class="power-card red-card">
                    <div class="card-left">
                      <div class="card-icon">
                        <i class="el-icon-data-line"></i>
                      </div>
                      <div class="card-title">尖段电量</div>
                    </div>
                    <div class="card-value-percentage">
                      {{
                        formatNumber(
                          companyTotalElectricityData.sharpElectricity
                        )
                      }}kWh,{{
                        formatNumber(
                          companyTotalElectricityData.sharpElectricityPercentage
                        )
                      }}%
                    </div>
                  </div>
                  <div class="power-card blue-card">
                    <div class="card-left">
                      <div class="card-icon">
                        <i class="el-icon-data-line"></i>
                      </div>
                      <div class="card-title">峰段电量</div>
                    </div>
                    <div class="card-value-percentage">
                      {{
                        formatNumber(
                          companyTotalElectricityData.peakElectricity
                        )
                      }}kWh,{{
                        formatNumber(
                          companyTotalElectricityData.peakElectricityPercentage
                        )
                      }}%
                    </div>
                  </div>
                  <div class="power-card green-card">
                    <div class="card-left">
                      <div class="card-icon">
                        <i class="el-icon-data-line"></i>
                      </div>
                      <div class="card-title">平段电量</div>
                    </div>
                    <div class="card-value-percentage">
                      {{
                        formatNumber(
                          companyTotalElectricityData.flatElectricity
                        )
                      }}kWh,{{
                        formatNumber(
                          companyTotalElectricityData.flatElectricityPercentage
                        )
                      }}%
                    </div>
                  </div>
                  <div class="power-card orange-card">
                    <div class="card-left">
                      <div class="card-icon">
                        <i class="el-icon-data-line"></i>
                      </div>
                      <div class="card-title">谷段电量</div>
                    </div>
                    <div class="card-value-percentage">
                      {{
                        formatNumber(
                          companyTotalElectricityData.valleyElectricity
                        )
                      }}kWh,{{
                        formatNumber(
                          companyTotalElectricityData.valleyElectricityPercentage
                        )
                      }}%
                    </div>
                  </div>
                </div>

                <!-- Right side: ECharts Pie Chart -->
                <div class="power-pie-chart-section">
                  <nt-echart
                    id="total-electric-pie-chart"
                    :options="companyElectricityPieOptions"
                    style="width: 100%; height: 300px"
                  ></nt-echart>
                </div>
              </div>

              <!-- 柱状图区域 -->
              <div style="margin-bottom: 20px">
                <div style="height: 300px; padding: 10px">
                  <nt-echart
                    id="total-electric-bar-chart"
                    :loading="loading"
                    :options="dailyElectricityChartOptions"
                  ></nt-echart>
                </div>
              </div>

              <!-- 详细数据表格 -->
              <div style="margin-top: 20px">
                <div
                  style="
                    font-weight: bold;
                    margin-bottom: 10px;
                    font-size: 14px;
                  "
                >
                  用电量详细数据
                </div>
                <el-table
                  :data="dailyElectricityTableData"
                  max-height="350"
                  border
                  style="width: 100%"
                  :header-cell-style="getHeaderCellStyle"
                >
                  <el-table-column
                    prop="dateStr"
                    label="时间"
                    min-width="120"
                    align="center"
                  >
                  </el-table-column>
                  <el-table-column
                    prop="sharpElectricity"
                    label="尖(kWh)"
                    min-width="100"
                    align="center"
                  >
                    <template slot-scope="scope">
                      {{ formatNumber(scope.row.sharpElectricity) }}
                    </template>
                  </el-table-column>
                  <el-table-column
                    prop="peakElectricity"
                    label="峰(kWh)"
                    min-width="100"
                    align="center"
                  >
                    <template slot-scope="scope">
                      {{ formatNumber(scope.row.peakElectricity) }}
                    </template>
                  </el-table-column>
                  <el-table-column
                    prop="flatElectricity"
                    label="平(kWh)"
                    min-width="100"
                    align="center"
                  >
                    <template slot-scope="scope">
                      {{ formatNumber(scope.row.flatElectricity) }}
                    </template>
                  </el-table-column>
                  <el-table-column
                    prop="valleyElectricity"
                    label="谷(kWh)"
                    min-width="100"
                    align="center"
                  >
                    <template slot-scope="scope">
                      {{ formatNumber(scope.row.valleyElectricity) }}
                    </template>
                  </el-table-column>
                  <el-table-column
                    prop="totalElectricity"
                    label="总电量(kWh)"
                    min-width="120"
                    align="center"
                  >
                    <template slot-scope="scope">
                      {{ formatNumber(scope.row.totalElectricity) }}
                    </template>
                  </el-table-column>
                  <el-table-column
                    prop="peakValleyRatio"
                    label="尖峰占比"
                    min-width="100"
                    align="center"
                  >
                    <template slot-scope="scope">
                      {{ formatNumber(scope.row.peakValleyRatio) }}%
                    </template>
                  </el-table-column>
                  <el-table-column
                    prop="degreeCharge"
                    label="电度电费(元)"
                    min-width="120"
                    align="center"
                  >
                    <template slot-scope="scope">
                      {{ formatNumber(scope.row.degreeCharge) }}
                    </template>
                  </el-table-column>
                  <el-table-column
                    prop="avgPrice"
                    label="平均电价(元/kWh)"
                    min-width="140"
                    align="center"
                  >
                    <template slot-scope="scope">
                      {{ formatNumber(scope.row.avgPrice) }}
                    </template>
                  </el-table-column>
                  <template slot="empty">
                    <div style="text-align: center; padding: 20px; color: #999">
                      暂无数据
                    </div>
                  </template>
                </el-table>
              </div>
            </div>

            <!-- 3.5 变压器用电量 -->
            <div style="margin-top: 30px">
              <div
                style="font-weight: bold; margin-bottom: 15px; font-size: 16px"
              >
                3.5 变压器用电量
              </div>

              <!-- 变压器用电量汇总表 -->
              <div style="margin-bottom: 20px">
                <el-table
                  :data="transformerElectricityData"
                  border
                  max-height="300"
                  style="width: 100%"
                  :header-cell-style="getHeaderCellStyle"
                >
                  <el-table-column
                    prop="name"
                    label="变压器"
                    min-width="100"
                    align="center"
                  >
                  </el-table-column>
                  <el-table-column label="尖" align="center">
                    <el-table-column
                      prop="sharpElectricity"
                      label="电量(kWh)"
                      min-width="100"
                      align="center"
                    >
                      <template slot-scope="scope">
                        {{ formatNumber(scope.row.sharpElectricity) }}
                      </template>
                    </el-table-column>
                    <el-table-column
                      prop="sharpElectricityFee"
                      label="电费(元)"
                      min-width="100"
                      align="center"
                    >
                      <template slot-scope="scope">
                        {{ formatNumber(scope.row.sharpElectricityFee) }}
                      </template>
                    </el-table-column>
                  </el-table-column>
                  <el-table-column label="峰" align="center">
                    <el-table-column
                      prop="peakElectricity"
                      label="电量(kWh)"
                      min-width="100"
                      align="center"
                    >
                      <template slot-scope="scope">
                        {{ formatNumber(scope.row.peakElectricity) }}
                      </template>
                    </el-table-column>
                    <el-table-column
                      prop="peakElectricityFee"
                      label="电费(元)"
                      min-width="100"
                      align="center"
                    >
                      <template slot-scope="scope">
                        {{ formatNumber(scope.row.peakElectricityFee) }}
                      </template>
                    </el-table-column>
                  </el-table-column>
                  <el-table-column label="平" align="center">
                    <el-table-column
                      prop="flatElectricity"
                      label="电量(kWh)"
                      min-width="100"
                      align="center"
                    >
                      <template slot-scope="scope">
                        {{ formatNumber(scope.row.flatElectricity) }}
                      </template>
                    </el-table-column>
                    <el-table-column
                      prop="flatElectricityFee"
                      label="电费(元)"
                      min-width="100"
                      align="center"
                    >
                      <template slot-scope="scope">
                        {{ formatNumber(scope.row.flatElectricityFee) }}
                      </template>
                    </el-table-column>
                  </el-table-column>
                  <el-table-column label="谷" align="center">
                    <el-table-column
                      prop="valleyElectricity"
                      label="电量(kWh)"
                      min-width="100"
                      align="center"
                    >
                      <template slot-scope="scope">
                        {{ formatNumber(scope.row.valleyElectricity) }}
                      </template>
                    </el-table-column>
                    <el-table-column
                      prop="valleyElectricityFee"
                      label="电费(元)"
                      min-width="100"
                      align="center"
                    >
                      <template slot-scope="scope">
                        {{ formatNumber(scope.row.valleyElectricityFee) }}
                      </template>
                    </el-table-column>
                  </el-table-column>
                  <template slot="empty">
                    <div style="text-align: center; padding: 20px; color: #999">
                      暂无数据
                    </div>
                  </template>
                </el-table>
              </div>

              <!-- 变压器电量结构图表 -->
              <div
                class="transformer-charts-grid"
                style="display: flex; flex-wrap: wrap; gap: 20px"
              >
                <div
                  v-for="(chartConfig, index) in transformerPieOptionsList"
                  :key="`pie-${index}-${chartConfig.id}`"
                  class="transformer-chart-item"
                  style="flex: 1; min-width: 45%; max-width: 48%"
                >
                  <div class="chart-title-left">
                    {{ chartConfig.name }}电量结构
                  </div>
                  <div
                    style="
                      width: 100%;
                      height: 300px;
                      padding: 10px;
                      min-width: 300px;
                    "
                  >
                    <nt-echart
                      class="transformer-pie-chart"
                      :loading="loading"
                      :options="chartConfig.options"
                    ></nt-echart>
                  </div>
                </div>
              </div>
            </div>

            <!-- 四、用电安全分析 -->
            <div style="margin-top: 30px">
              <div
                style="font-weight: bold; margin-bottom: 15px; font-size: 16px"
              >
                四、用电安全分析
              </div>

              <!-- 4.1 事件分析 -->
              <div style="margin-top: 20px">
                <div
                  style="
                    font-weight: bold;
                    margin-bottom: 15px;
                    font-size: 14px;
                  "
                >
                  4.1 事件分析
                </div>

                <!-- 事件分析表格 -->
                <div style="margin-bottom: 20px">
                  <el-table
                    :data="eventAnalysisData"
                    border
                    max-height="300"
                    style="width: 100%"
                    :header-cell-style="getHeaderCellStyle"
                  >
                    <el-table-column
                      type="index"
                      label="序号"
                      width="100"
                      align="center"
                    >
                    </el-table-column>
                    <el-table-column
                      prop="equipName"
                      label="设备"
                      align="center"
                    >
                    </el-table-column>
                    <el-table-column
                      prop="seriousAlarmNum"
                      label="严重告警"
                      min-width="50"
                      align="center"
                    >
                      <template slot-scope="scope">{{
                        formatNumber(scope.row.seriousAlarmNum)
                      }}</template>
                    </el-table-column>
                    <el-table-column
                      prop="normalAlarmNum"
                      label="普通告警"
                      min-width="50"
                      align="center"
                    >
                      <template slot-scope="scope">{{
                        formatNumber(scope.row.normalAlarmNum)
                      }}</template>
                    </el-table-column>
                    <el-table-column
                      prop="generalAlarmNum"
                      label="一般告警"
                      min-width="50"
                      align="center"
                    >
                      <template slot-scope="scope">{{
                        formatNumber(scope.row.generalAlarmNum)
                      }}</template>
                    </el-table-column>
                    <el-table-column
                      prop="minorAlarmNum"
                      label="轻微告警"
                      min-width="50"
                      align="center"
                    >
                      <template slot-scope="scope">{{
                        formatNumber(scope.row.minorAlarmNum)
                      }}</template>
                    </el-table-column>
                    <template slot="empty">
                      <div
                        style="text-align: center; padding: 20px; color: #999"
                      >
                        暂无数据
                      </div>
                    </template>
                  </el-table>
                </div>
              </div>
            </div>

            <!-- 五、变压器分析 -->
            <div style="margin-top: 30px">
              <div
                style="font-weight: bold; margin-bottom: 15px; font-size: 16px"
              >
                五、变压器分析
              </div>

              <!-- 5.1 变压器负荷分析 -->
              <div style="margin-top: 20px">
                <div
                  style="
                    font-weight: bold;
                    margin-bottom: 15px;
                    font-size: 14px;
                  "
                >
                  5.1 变压器负荷分析
                </div>

                <!-- 说明段落 -->
                <div
                  style="
                    margin-bottom: 20px;
                    line-height: 1.8;
                    font-size: 14px;
                    text-align: justify;
                  "
                >
                  <p>
                    变压器合理运行对用户用电安全、电网可靠性和经济运行具有重要意义。变压器容量选择过大，会造成资金浪费，变压器容量选择过小，负载转移能力差，安全可靠性低。
                  </p>
                </div>

                <!-- 变压器负荷分析表格 -->
                <div style="margin-bottom: 20px">
                  <el-table
                    :data="transformerLoadData"
                    border
                    style="width: 100%"
                    :header-cell-style="getHeaderCellStyle"
                  >
                    <el-table-column
                      type="index"
                      label="序号"
                      width="80"
                      align="center"
                    ></el-table-column>
                    <el-table-column
                      prop="equipmentName"
                      label="设备"
                      min-width="120"
                      align="center"
                    >
                      <template slot-scope="scope">{{
                        scope.row.equipmentName || scope.row.name || '-'
                      }}</template>
                    </el-table-column>
                    <el-table-column
                      prop="ratedCapacity"
                      label="额定容量"
                      min-width="100"
                      align="center"
                    >
                      <template slot-scope="scope">{{
                        formatNumber(scope.row.ratedCapacity)
                      }}</template>
                    </el-table-column>
                    <el-table-column
                      prop="electricity"
                      label="当月电量 (kWh)"
                      min-width="120"
                      align="center"
                    >
                      <template slot-scope="scope">{{
                        formatNumber(scope.row.electricity)
                      }}</template>
                    </el-table-column>
                    <el-table-column
                      prop="maxLoad"
                      label="最大负荷 (kW)"
                      min-width="120"
                      align="center"
                    >
                      <template slot-scope="scope">{{
                        formatNumber(scope.row.maxLoad)
                      }}</template>
                    </el-table-column>
                    <el-table-column
                      prop="maxLoadTime"
                      label="最大负荷时间"
                      min-width="160"
                      align="center"
                    >
                      <template slot-scope="scope">{{
                        scope.row.maxLoadTime || '-'
                      }}</template>
                    </el-table-column>
                    <el-table-column
                      prop="averageLoadRate"
                      label="月平均负载率 (%)"
                      min-width="140"
                      align="center"
                    >
                      <template slot-scope="scope">{{
                        formatNumber(scope.row.averageLoadRate)
                      }}</template>
                    </el-table-column>
                    <el-table-column
                      prop="economicEvaluation"
                      label="经济评估"
                      min-width="100"
                      align="center"
                    >
                      <template slot-scope="scope">
                        {{ formatNumber(scope.row.economicEvaluation) }}
                      </template>
                    </el-table-column>
                    <template slot="empty">
                      <div
                        style="text-align: center; padding: 20px; color: #999"
                      >
                        暂无数据
                      </div>
                    </template>
                  </el-table>
                </div>

                <!-- 变压器负荷图表 -->
                <div class="transformer-load-charts-vertical">
                  <div
                    v-for="(
                      chartConfig, index
                    ) in transformerLoadChartOptionsList"
                    :key="`load-${index}-${chartConfig.id}`"
                    class="load-chart-item-vertical"
                  >
                    <div class="chart-title-left">{{ chartConfig.name }}</div>
                    <div
                      style="
                        width: 100%;
                        height: 300px;
                        padding: 10px;
                        margin-top: 15px;
                      "
                    >
                      <nt-echart
                        class="transformer-load-chart"
                        :loading="loading"
                        :options="chartConfig.options"
                      ></nt-echart>
                    </div>
                  </div>

                  <!-- 如果没有数据，显示提示 -->
                  <div
                    v-if="transformerLoadData.length === 0"
                    class="load-chart-item-vertical"
                  >
                    <div class="chart-title-left">变压器负荷分析</div>
                    <div
                      style="
                        height: 300px;
                        background: #f8f9fa;
                        border: 1px solid #e9ecef;
                        border-radius: 4px;
                        display: flex;
                        align-items: center;
                        justify-content: center;
                        color: #6c757d;
                        font-size: 14px;
                        margin-top: 15px;
                      "
                    >
                      暂无变压器负荷分析数据
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- 六、电能质量分析 -->
            <div style="margin-top: 30px">
              <div
                style="font-weight: bold; margin-bottom: 15px; font-size: 16px"
              >
                六、电能质量分析
              </div>

              <!-- 6.1 功率因数分析 -->
              <div style="margin-top: 20px">
                <div
                  style="
                    font-weight: bold;
                    margin-bottom: 15px;
                    font-size: 14px;
                  "
                >
                  6.1 功率因数分析
                </div>

                <!-- 说明段落 -->
                <div
                  style="
                    margin-bottom: 20px;
                    line-height: 1.8;
                    font-size: 14px;
                    text-align: justify;
                  "
                >
                  <p>
                    功率因数是衡星用电系统效率的一个经济指标,它由系统负荷性质决定。目前,商业用户功率因数考核的标准值为0.9。功率因数大于0.9,则力调电费有奖励;功率因数小于0.9,则力调电费有罚款。
                  </p>
                </div>

                <!-- 功率因数分析表格 -->
                <div style="margin-bottom: 20px">
                  <el-table
                    :data="powerFactorData"
                    border
                    max-height="300px"
                    style="width: 100%"
                    :header-cell-style="getHeaderCellStyle"
                  >
                    <el-table-column
                      type="index"
                      label="序号"
                      width="80"
                      align="center"
                    ></el-table-column>
                    <el-table-column
                      prop="equipmentName"
                      label="设备"
                      min-width="120"
                      align="center"
                    >
                      <template slot-scope="scope">{{
                        scope.row.equipmentName || scope.row.name || '-'
                      }}</template>
                    </el-table-column>
                    <el-table-column
                      prop="positiveActiveTotalElectricity"
                      label="正向有功总电能(kWh)"
                      min-width="140"
                      align="center"
                    >
                      <template slot-scope="scope">{{
                        formatNumber(scope.row.positiveActiveTotalElectricity)
                      }}</template>
                    </el-table-column>
                    <el-table-column
                      prop="positiveReactiveTotalElectricity"
                      label="正向无功总电能(kWh)"
                      min-width="140"
                      align="center"
                    >
                      <template slot-scope="scope">{{
                        formatNumber(scope.row.positiveReactiveTotalElectricity)
                      }}</template>
                    </el-table-column>
                    <el-table-column
                      prop="averagePowerFactor"
                      label="平均功率因数"
                      min-width="140"
                      align="center"
                    >
                      <template slot-scope="scope">{{
                        formatNumber(scope.row.averagePowerFactor)
                      }}</template>
                    </el-table-column>
                    <el-table-column
                      prop="conclusion"
                      label="结论"
                      min-width="100"
                      align="center"
                    >
                      <template slot-scope="scope">
                        {{ formatNumber(scope.row.conclusion) }}
                      </template>
                    </el-table-column>
                    <template slot="empty">
                      <div
                        style="text-align: center; padding: 20px; color: #999"
                      >
                        暂无数据
                      </div>
                    </template>
                  </el-table>
                </div>

                <!-- 功率因数图表 -->
                <div style="margin-top: 20px">
                  <div
                    style="
                      font-weight: bold;
                      margin-bottom: 15px;
                      font-size: 14px;
                    "
                  >
                    月度日平均功率因数
                  </div>
                  <div style="width: 100%; height: 300px; padding: 10px">
                    <nt-echart
                      id="power-factor-chart"
                      :loading="loading"
                      :options="powerFactorChartOptions"
                    ></nt-echart>
                  </div>
                </div>

                <!-- 6.2 三相不平衡分析 -->
                <div style="margin-top: 30px">
                  <div
                    style="
                      font-weight: bold;
                      margin-bottom: 15px;
                      font-size: 14px;
                    "
                  >
                    6.2 三相不平衡分析
                  </div>

                  <!-- 说明段落 -->
                  <div
                    style="
                      margin-bottom: 20px;
                      line-height: 1.8;
                      font-size: 14px;
                      text-align: justify;
                    "
                  >
                    <p>
                      三相不平衡会造成三相负荷严重不对称,中性点电位就会发生偏移,线路压降和功率损失就会大大增加。
                    </p>
                  </div>

                  <!-- 三相不平衡分析表格 -->
                  <el-table
                    :data="threePhaseUnbalanceData"
                    border
                    max-height="300px"
                    style="width: 100%"
                    :header-cell-style="getHeaderCellStyle"
                  >
                    <el-table-column
                      type="index"
                      label="序号"
                      width="80"
                      align="center"
                    ></el-table-column>
                    <el-table-column
                      prop="name"
                      label="设备"
                      min-width="120"
                      align="center"
                    >
                      <template slot-scope="scope">{{
                        scope.row.name || '-'
                      }}</template>
                    </el-table-column>
                    <el-table-column
                      prop="threePhaseCurrentImbalance"
                      label="三相电流不平衡度"
                      min-width="140"
                      align="center"
                    >
                      <template slot-scope="scope">{{
                        formatNumber(scope.row.threePhaseCurrentImbalance)
                      }}</template>
                    </el-table-column>
                    <el-table-column
                      prop="threePhaseCurrentImbalanceConclusion"
                      label="三相电流不平衡结论"
                      min-width="140"
                      align="center"
                    >
                      <template slot-scope="scope">{{
                        scope.row.threePhaseCurrentImbalanceConclusion || '-'
                      }}</template>
                    </el-table-column>
                    <el-table-column
                      prop="threePhaseVoltageImbalance"
                      label="三相电压不平衡度"
                      min-width="140"
                      align="center"
                    >
                      <template slot-scope="scope">{{
                        formatNumber(scope.row.threePhaseVoltageImbalance)
                      }}</template>
                    </el-table-column>
                    <el-table-column
                      prop="threePhaseVoltageImbalanceConclusion"
                      label="三相电压不平衡结论"
                      min-width="140"
                      align="center"
                    >
                      <template slot-scope="scope">{{
                        scope.row.threePhaseVoltageImbalanceConclusion || '-'
                      }}</template>
                    </el-table-column>
                    <template slot="empty">
                      <div
                        style="text-align: center; padding: 20px; color: #999"
                      >
                        暂无数据
                      </div>
                    </template>
                  </el-table>
                </div>

                <!-- 6.3 电压偏差分析 -->
                <div style="margin-top: 30px">
                  <div
                    style="
                      font-weight: bold;
                      margin-bottom: 15px;
                      font-size: 14px;
                    "
                  >
                    6.3 电压偏差分析
                  </div>

                  <!-- 电压偏差分析表格 -->
                  <el-table
                    :data="voltageDeviationData"
                    border
                    max-height="400px"
                    style="width: 100%"
                    :header-cell-style="getHeaderCellStyle"
                  >
                    <el-table-column
                      type="index"
                      label="序号"
                      width="80"
                      align="center"
                    ></el-table-column>
                    <el-table-column
                      prop="name"
                      label="设备"
                      min-width="140"
                      align="center"
                    >
                      <template slot-scope="scope">{{
                        scope.row.name || '-'
                      }}</template>
                    </el-table-column>

                    <!-- 电压越上限标准(V) -->
                    <el-table-column label="电压越上限标准(V)" align="center">
                      <el-table-column
                        prop="aPhaseUpperLimit"
                        label="A相"
                        min-width="90"
                        align="center"
                      >
                        <template slot-scope="scope">{{
                          formatNumber(scope.row.aPhaseUpperLimit)
                        }}</template>
                      </el-table-column>
                      <el-table-column
                        prop="bPhaseUpperLimit"
                        label="B相"
                        min-width="90"
                        align="center"
                      >
                        <template slot-scope="scope">{{
                          formatNumber(scope.row.bPhaseUpperLimit)
                        }}</template>
                      </el-table-column>
                      <el-table-column
                        prop="cPhaseUpperLimit"
                        label="C相"
                        min-width="90"
                        align="center"
                      >
                        <template slot-scope="scope">{{
                          formatNumber(scope.row.cPhaseUpperLimit)
                        }}</template>
                      </el-table-column>
                    </el-table-column>

                    <!-- 电压越下限标准(V) -->
                    <el-table-column label="电压越下限标准(V)" align="center">
                      <el-table-column
                        prop="aPhaseLowerLimit"
                        label="A相"
                        min-width="90"
                        align="center"
                      >
                        <template slot-scope="scope">{{
                          formatNumber(scope.row.aPhaseLowerLimit)
                        }}</template>
                      </el-table-column>
                      <el-table-column
                        prop="bPhaseLowerLimit"
                        label="B相"
                        min-width="90"
                        align="center"
                      >
                        <template slot-scope="scope">{{
                          formatNumber(scope.row.bPhaseLowerLimit)
                        }}</template>
                      </el-table-column>
                      <el-table-column
                        prop="cPhaseLowerLimit"
                        label="C相"
                        min-width="90"
                        align="center"
                      >
                        <template slot-scope="scope">{{
                          formatNumber(scope.row.cPhaseLowerLimit)
                        }}</template>
                      </el-table-column>
                    </el-table-column>

                    <!-- 最高电压(V) -->
                    <el-table-column label="最高电压(V)" align="center">
                      <el-table-column
                        prop="aPhaseMaxVoltage"
                        label="A相"
                        min-width="90"
                        align="center"
                      >
                        <template slot-scope="scope">{{
                          formatNumber(scope.row.aPhaseMaxVoltage)
                        }}</template>
                      </el-table-column>
                      <el-table-column
                        prop="bPhaseMaxVoltage"
                        label="B相"
                        min-width="90"
                        align="center"
                      >
                        <template slot-scope="scope">{{
                          formatNumber(scope.row.bPhaseMaxVoltage)
                        }}</template>
                      </el-table-column>
                      <el-table-column
                        prop="cPhaseMaxVoltage"
                        label="C相"
                        min-width="90"
                        align="center"
                      >
                        <template slot-scope="scope">{{
                          formatNumber(scope.row.cPhaseMaxVoltage)
                        }}</template>
                      </el-table-column>
                    </el-table-column>

                    <!-- 最低电压(V) -->
                    <el-table-column label="最低电压(V)" align="center">
                      <el-table-column
                        prop="aPhaseMinVoltage"
                        label="A相"
                        min-width="90"
                        align="center"
                      >
                        <template slot-scope="scope">{{
                          formatNumber(scope.row.aPhaseMinVoltage)
                        }}</template>
                      </el-table-column>
                      <el-table-column
                        prop="bPhaseMinVoltage"
                        label="B相"
                        min-width="90"
                        align="center"
                      >
                        <template slot-scope="scope">{{
                          formatNumber(scope.row.bPhaseMinVoltage)
                        }}</template>
                      </el-table-column>
                      <el-table-column
                        prop="cPhaseMinVoltage"
                        label="C相"
                        min-width="90"
                        align="center"
                      >
                        <template slot-scope="scope">{{
                          formatNumber(scope.row.cPhaseMinVoltage)
                        }}</template>
                      </el-table-column>
                    </el-table-column>

                    <template slot="empty">
                      <div
                        style="text-align: center; padding: 20px; color: #999"
                      >
                        暂无数据
                      </div>
                    </template>
                  </el-table>

                  <!-- 电压偏差分析说明 -->
                  <div
                    style="
                      margin-top: 20px;
                      line-height: 1.8;
                      font-size: 14px;
                      text-align: justify;
                    "
                  >
                    <p style="margin-bottom: 15px">
                      从以上表中,可以看出红色图标表示最高电压越限,绿色图标表示最低电压越限,电压远远超额定电压,可适当调整变压器档位,使变压电压过高不仅冲击电力系统的稳定以及对电气设备的损害,还会增加用电量。分析依据:电能质星供电电压允许偏差》GB/T12325-2008)。
                    </p>
                    <p style="margin-bottom: 15px">
                      依据内容:20kV及以下三相供电电压偏差为标称电压的土7%。220V单相供电为+7%,
                      -10%
                    </p>
                    <p style="margin-bottom: 15px">
                      电压是主要电性能指标之一,电压高低及质量的好坏对用电设备的运行产生较大影响:浪费电能;安全隐患增加。
                    </p>
                    <p style="margin-bottom: 15px">
                      电压偏差将影响电能质量,影响对电能的正常和安全应用。电压偏差是实际电压偏离额定值,出现过电压(偏高)或低电压(偏低)。
                    </p>
                    <p>
                      实际电压偏高将造成设备过电压,威胁绝综和降低使用寿命;实际电压偏低,将影响用户的设备正常工作,使用户设备和电器不能正常运行或停正运行。
                    </p>
                  </div>
                </div>

                <!-- 6.4 谐波分析 -->
                <div style="margin-top: 30px">
                  <div
                    style="
                      font-weight: bold;
                      margin-bottom: 15px;
                      font-size: 14px;
                    "
                  >
                    6.4 谐波分析
                  </div>

                  <!-- 谐波分析表格 -->
                  <el-table
                    :data="harmonicAnalysisData"
                    border
                    max-height="400px"
                    style="width: 100%"
                    :header-cell-style="getHeaderCellStyle"
                  >
                    <el-table-column
                      type="index"
                      label="序号"
                      width="80"
                      align="center"
                    ></el-table-column>
                    <el-table-column
                      prop="name"
                      label="设备"
                      min-width="140"
                      align="center"
                    >
                      <template slot-scope="scope">{{
                        scope.row.name || '-'
                      }}</template>
                    </el-table-column>
                    <el-table-column
                      prop="threePhaseVoltageHarmonic"
                      label="三相电压谐波"
                      min-width="140"
                      align="center"
                    >
                      <template slot-scope="scope">{{
                        formatNumber(scope.row.threePhaseVoltageHarmonic)
                      }}</template>
                    </el-table-column>
                    <el-table-column
                      prop="threePhaseVoltageHarmonicConclusion"
                      label="三相电压谐波结论"
                      min-width="160"
                      align="center"
                    >
                      <template slot-scope="scope">{{
                        scope.row.threePhaseVoltageHarmonicConclusion || '-'
                      }}</template>
                    </el-table-column>
                    <el-table-column
                      prop="threePhaseCurrentHarmonic"
                      label="三相电流谐波"
                      min-width="140"
                      align="center"
                    >
                      <template slot-scope="scope">{{
                        formatNumber(scope.row.threePhaseCurrentHarmonic)
                      }}</template>
                    </el-table-column>
                    <el-table-column
                      prop="threePhaseCurrentHarmonicConclusion"
                      label="三相电流谐波结论"
                      min-width="160"
                      align="center"
                    >
                      <template slot-scope="scope">{{
                        scope.row.threePhaseCurrentHarmonicConclusion || '-'
                      }}</template>
                    </el-table-column>
                    <template slot="empty">
                      <div
                        style="text-align: center; padding: 20px; color: #999"
                      >
                        暂无数据
                      </div>
                    </template>
                  </el-table>

                  <!-- 谐波的主要危害 -->
                  <div style="margin-top: 20px">
                    <div
                      style="
                        font-weight: bold;
                        margin-bottom: 15px;
                        font-size: 14px;
                      "
                    >
                      谐波的主要危害
                    </div>
                    <div
                      style="
                        line-height: 1.8;
                        font-size: 14px;
                        text-align: justify;
                      "
                    >
                      <ul style="margin: 0; padding-left: 20px">
                        <li style="margin-bottom: 10px">
                          谐波的存在,使电压突变造成电子设备损坏、电子设备出现误动作。
                        </li>
                        <li style="margin-bottom: 10px">
                          使电力变压器线圈发热,加速绝缘老化,寿命缩短、引起附加损耗和噪音。
                        </li>
                        <li style="margin-bottom: 10px">
                          对断路器、漏电保护器、继电器等保护、自控装置产生干扰,造成误动作。
                        </li>
                        <li style="margin-bottom: 10px">
                          使照明设备寿命缩短。
                        </li>
                        <li style="margin-bottom: 10px">
                          造成电流表、电压表、功率表、电能表测量误差。
                        </li>
                        <li style="margin-bottom: 10px">
                          对临近的通讯线路产生静电干扰和电磁干扰。
                        </li>
                        <li style="margin-bottom: 10px">
                          使配电线路损耗增大、发热、缩短绝缘寿命,甚至引起短路、火灾。
                        </li>
                        <li style="margin-bottom: 10px">
                          使电动机产生附加损耗和发热、产生脉动转矩和噪音。
                        </li>
                        <li style="margin-bottom: 10px">
                          影响计算机系统正常运行,造成数据丢失,甚至损坏硬件。引起楼宇自动化、消防报警系统、安全防范系统误动作,甚至无法工作。
                        </li>
                      </ul>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- 七、用能建议 -->
            <div style="margin-top: 30px">
              <div
                style="font-weight: bold; margin-bottom: 20px; font-size: 16px"
              >
                七、用能建议
              </div>

              <!-- 用能建议列表 -->
              <div
                style="line-height: 1.8; font-size: 14px; text-align: justify"
              >
                <ol style="margin: 0; padding-left: 20px">
                  <li style="margin-bottom: 15px">
                    <strong>选择合理的基本电费套餐：</strong
                    >如负载率长期低于60%,选择按需量申报。按照已发行电费月份举例说明调整基本电费的收益。
                  </li>
                  <li style="margin-bottom: 15px">
                    <strong>加强无功补偿处理：</strong
                    >对于无功补偿欠佳的单位,提供无功补偿建议,预估投入产出比。
                  </li>
                  <li style="margin-bottom: 15px">
                    <strong>合理安排生产工艺：</strong
                    >初步判断负荷毛刺的原因,提出错峰启用主要用电设备的建议。对于尖峰用电占比较高的单位,建议进行负荷调优,合理优化负荷曲线。
                  </li>
                  <li style="margin-bottom: 15px">
                    <strong>适时开展节能改造：</strong
                    >针对能耗偏高、能效偏低的用电设备,提出节能改造建议,预估节能改造的投资回报情况。
                  </li>
                </ol>
              </div>

              <!-- 说明 -->
              <div
                style="
                  margin-top: 25px;
                  line-height: 1.8;
                  font-size: 14px;
                  text-align: justify;
                "
              >
                <p style="margin: 0">
                  <strong>说明：</strong
                  >因电能监测终端的安装位置、采集精度、统计周期与电网公司计量设备存在较大差异,本报告不作为用电企业与售电公司电费结算的依据,是电力服务公司或企业设备管理人员日常管理配用电设备及优化用电方式的辅助决策依据。
                </p>
              </div>
            </div>
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="generateDialogVisible = false">关 闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getCompanyListApi,
  getElectricRunReportListApi,
  generateElectricRunReportApi,
  viewElectricRunReportApi,
  deleteElectricRunReportApi,
  saveElectricRunReportPictureApi,
  downloadElectricRunReportApi
} from '@/api/Distribution/maintenance-report'
import { exportexcel } from '@/utils/excel'
import FilterSelect2 from '@/components/FilterSelect2/index.vue'
import TopTile from '@/components/TopTitle/index.vue'
import Twobtn from '@/components/Twobtn/index.vue'
import ntEchart from '@/components/nt-echart.vue'
import download from 'downloadjs'

export default {
  name: 'MaintenanceReport',
  components: {
    FilterSelect2,
    TopTile,
    Twobtn,
    ntEchart
  },
  data() {
    return {
      form: {
        orgNo: '', // 企业编码（接口参数）
        startMonth: '',
        endMonth: ''
      },
      dateRange: [],
      companyList: [],
      loading: false,
      downloadLoading: false,
      tableData: [],
      total: 0,
      pageobj: {
        _pageNo: 1,
        _pageSize: 10
      },
      iissize: 'medium',
      generateDialogVisible: false,
      generateLoading: false,
      currentRow: {},
      generateForm: {
        remark: ''
      },
      // 报告数据
      reportData: null
    }
  },
  async mounted() {
    await this.getCompanyList()
    this.setDefaultDateRange()
    await this.getdatalist()
  },
  computed: {
    // 处理用电基本情况数据，将 Map 结构转换为数组
    electricityBasicDataList() {
      if (!this.reportData || !this.reportData.electricityBasicData) {
        return []
      }

      const result = []
      let serialNumber = 1

      // 遍历 electricityBasicData 对象
      Object.keys(this.reportData.electricityBasicData).forEach(
        (monitorClass) => {
          const items = this.reportData.electricityBasicData[monitorClass]
          if (items && items.length > 0) {
            items.forEach((item, index) => {
              result.push({
                序号: serialNumber++,
                监测类: monitorClass,
                监测类RowSpan: index === 0 ? items.length : 0,
                监测项: item.name || '-',
                监测标准: item.standard || '-',
                得分: item.score || 0,
                评价: item.evaluate || '-'
              })
            })
          }
        }
      )

      return result
    },

    // 处理电量电费概况数据
    electricityViewData() {
      if (!this.reportData || !this.reportData.electricityView) {
        return {}
      }

      try {
        // 如果 electricityView 是字符串，尝试解析为 JSON
        if (typeof this.reportData.electricityView === 'string') {
          return JSON.parse(this.reportData.electricityView)
        }
        // 如果已经是对象，直接返回
        return this.reportData.electricityView
      } catch (error) {
        console.error('解析 electricityView 数据失败:', error)
        return {}
      }
    },

    // 处理负荷情况数据
    loadViewData() {
      if (!this.reportData || !this.reportData.loadView) {
        return {}
      }

      try {
        // 如果 loadView 是字符串，尝试解析为 JSON
        if (typeof this.reportData.loadView === 'string') {
          return JSON.parse(this.reportData.loadView)
        }
        // 如果已经是对象，直接返回
        return this.reportData.loadView
      } catch (error) {
        console.error('解析 loadView 数据失败:', error)
        return {}
      }
    },

    // 负荷特性曲线图表配置
    loadCurveOptions() {
      if (
        !this.loadViewData.thisMonthLoadCurve ||
        !Array.isArray(this.loadViewData.thisMonthLoadCurve)
      ) {
        return {
          title: {
            text: '暂无数据',
            left: 'center',
            top: 'middle',
            textStyle: {
              color: '#999',
              fontSize: 14
            }
          }
        }
      }

      return {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'line'
          }
        },
        legend: {
          bottom: 10
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '15%',
          top: '10%',
          containLabel: true
        },
        xAxis: {
          type: 'category'
        },
        yAxis: {
          type: 'value',
          name: '单位:(kW)'
        },
        series: this.loadViewData.thisMonthLoadCurve
          .sort((a, b) => {
            // 按名称排序：最大负荷、平均负荷、最小负荷
            const order = { 最大负荷: 0, 平均负荷: 1, 最小负荷: 2 }
            const aOrder = order[a.name] ?? 999
            const bOrder = order[b.name] ?? 999
            return aOrder - bOrder
          })
          .map((curve, index) => {
            // 颜色顺序：#659eff #ffe66a #1ff2d0
            const colors = ['#659eff', '#ffe66a', '#1ff2d0']
            return {
              name: curve.name || '负荷曲线',
              type: 'line',
              smooth: true,
              symbol: 'emptyCircle', // 空心圆
              symbolSize: 4,
              itemStyle: {
                color: colors[index] || '#659eff'
              },
              lineStyle: {
                width: 2,
                color: colors[index] || '#659eff'
              },
              data: curve.datalist?.map((item) => {
                return [item.timeReading, parseFloat(item.valueReading) || 0]
              })
            }
          })
      }
    },

    // 典型日负荷曲线图表配置
    typicalDayLoadCurveOptions() {
      if (
        !this.loadViewData.typicalDayLoadCurve ||
        !Array.isArray(this.loadViewData.typicalDayLoadCurve)
      ) {
        return {
          title: {
            text: '暂无数据',
            left: 'center',
            top: 'middle',
            textStyle: {
              color: '#999',
              fontSize: 14
            }
          }
        }
      }

      return {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'line'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '15%',
          top: '10%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false
        },
        yAxis: {
          type: 'value',
          name: '单位:(kW)'
        },
        series: this.loadViewData.typicalDayLoadCurve.map((curve) => {
          return {
            name: curve.name || '典型日负荷曲线',
            type: 'line',
            smooth: true,
            symbol: 'emptyCircle',
            symbolSize: 4,
            itemStyle: {
              color: '#659eff' // 蓝色
            },
            lineStyle: {
              width: 2,
              color: '#659eff' // 蓝色
            },
            data: curve.datalist?.map((item) => {
              return [item.timeReading, parseFloat(item.valueReading) || 0]
            })
          }
        })
      }
    },

    // 电价分析图表配置
    electricityPriceOptions() {
      if (!this.reportData || !this.reportData.priceView) {
        return {
          title: {
            text: '暂无数据',
            left: 'center',
            top: 'middle',
            textStyle: {
              color: '#999',
              fontSize: 14
            }
          }
        }
      }

      // 解析电价数据
      let priceData = {}
      try {
        if (typeof this.reportData.priceView === 'string') {
          priceData = JSON.parse(this.reportData.priceView)
        } else {
          priceData = this.reportData.priceView
        }
      } catch (error) {
        console.error('解析电价数据失败:', error)
        return {
          title: {
            text: '数据解析失败',
            left: 'center',
            top: 'middle',
            textStyle: {
              color: '#999',
              fontSize: 14
            }
          }
        }
      }

      // 生成24小时电价数据
      const generatePriceData = () => {
        const data = []

        // 创建时间到电价的映射
        const timePriceMap = {}

        // 处理各时段数据
        if (priceData.sharpTimeList && priceData.sharpElectricityPrice) {
          priceData.sharpTimeList.forEach((time) => {
            if (time) {
              const hour = parseInt(time.substring(0, 2))
              const minute = parseInt(time.substring(2, 4))
              const timeKey = `${hour.toString().padStart(2, '0')}:${minute
                .toString()
                .padStart(2, '0')}`
              timePriceMap[timeKey] = priceData.sharpElectricityPrice
            }
          })
        }

        if (priceData.peakTimeList && priceData.peakElectricityPrice) {
          priceData.peakTimeList.forEach((time) => {
            if (time) {
              const hour = parseInt(time.substring(0, 2))
              const minute = parseInt(time.substring(2, 4))
              const timeKey = `${hour.toString().padStart(2, '0')}:${minute
                .toString()
                .padStart(2, '0')}`
              timePriceMap[timeKey] = priceData.peakElectricityPrice
            }
          })
        }

        if (priceData.flatTimeList && priceData.flatElectricityPrice) {
          priceData.flatTimeList.forEach((time) => {
            if (time) {
              const hour = parseInt(time.substring(0, 2))
              const minute = parseInt(time.substring(2, 4))
              const timeKey = `${hour.toString().padStart(2, '0')}:${minute
                .toString()
                .padStart(2, '0')}`
              timePriceMap[timeKey] = priceData.flatElectricityPrice
            }
          })
        }

        if (priceData.valleyTimeList && priceData.valleyElectricityPrice) {
          priceData.valleyTimeList.forEach((time) => {
            if (time) {
              const hour = parseInt(time.substring(0, 2))
              const minute = parseInt(time.substring(2, 4))
              const timeKey = `${hour.toString().padStart(2, '0')}:${minute
                .toString()
                .padStart(2, '0')}`
              timePriceMap[timeKey] = priceData.valleyElectricityPrice
            }
          })
        }

        // 生成24小时数据点
        for (let hour = 0; hour < 24; hour++) {
          for (let minute = 0; minute < 60; minute += 15) {
            const timeKey = `${hour.toString().padStart(2, '0')}:${minute
              .toString()
              .padStart(2, '0')}`
            const price = timePriceMap[timeKey] || 0
            data.push([timeKey, price])
          }
        }

        return data
      }

      return {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'line'
          },
          formatter: function (params) {
            const time = params[0].axisValue
            const price = params[0].value[1]
            return `时间: ${time}<br/>电价: ${price}元/kWh`
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '15%',
          top: '10%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '电价',
            type: 'line',
            step: 'after', // 阶梯线
            symbol: 'none', // 不显示数据点
            lineStyle: {
              width: 3,
              color: '#ff8c00' // 橙色
            },
            data: generatePriceData(),
            markArea: {
              emphasis: {
                disabled: true
              },
              data: this.generateUnifiedMarkAreas(priceData)
            }
          }
        ]
      }
    },

    // 处理企业总用电量数据
    companyTotalElectricityData() {
      if (
        !this.reportData ||
        !this.reportData.companyTotalElectricityView ||
        !Array.isArray(this.reportData.companyTotalElectricityView)
      ) {
        return {
          sharpElectricity: 0,
          peakElectricity: 0,
          flatElectricity: 0,
          valleyElectricity: 0,
          totalElectricity: 0,
          avgPrice: 0,
          sharpElectricityPercentage: 0,
          peakElectricityPercentage: 0,
          flatElectricityPercentage: 0,
          valleyElectricityPercentage: 0
        }
      }

      // 获取数组中的最后一个元素（合计数据）
      const totalData =
        this.reportData.companyTotalElectricityView[
          this.reportData.companyTotalElectricityView.length - 1
        ]

      if (!totalData) {
        return {
          sharpElectricity: 0,
          peakElectricity: 0,
          flatElectricity: 0,
          valleyElectricity: 0,
          totalElectricity: 0,
          avgPrice: 0,
          sharpElectricityPercentage: 0,
          peakElectricityPercentage: 0,
          flatElectricityPercentage: 0,
          valleyElectricityPercentage: 0
        }
      }

      const totalElectricity = parseFloat(totalData.totalElectricity) || 0
      const sharpElectricity = parseFloat(totalData.sharpElectricity) || 0
      const peakElectricity = parseFloat(totalData.peakElectricity) || 0
      const flatElectricity = parseFloat(totalData.flatElectricity) || 0
      const valleyElectricity = parseFloat(totalData.valleyElectricity) || 0

      return {
        sharpElectricity,
        peakElectricity,
        flatElectricity,
        valleyElectricity,
        totalElectricity,
        avgPrice: parseFloat(totalData.avgPrice) || 0,
        sharpElectricityPercentage:
          totalElectricity > 0
            ? ((sharpElectricity / totalElectricity) * 100).toFixed(2)
            : 0,
        peakElectricityPercentage:
          totalElectricity > 0
            ? ((peakElectricity / totalElectricity) * 100).toFixed(2)
            : 0,
        flatElectricityPercentage:
          totalElectricity > 0
            ? ((flatElectricity / totalElectricity) * 100).toFixed(2)
            : 0,
        valleyElectricityPercentage:
          totalElectricity > 0
            ? ((valleyElectricity / totalElectricity) * 100).toFixed(2)
            : 0
      }
    },

    // 企业用电量饼图配置
    companyElectricityPieOptions() {
      const data = this.companyTotalElectricityData

      return {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'horizontal',
          bottom: 10,
          data: ['尖', '峰', '平', '谷']
        },
        series: [
          {
            name: '用电量',
            type: 'pie',
            radius: ['40%', '70%'],
            center: ['50%', '45%'],
            avoidLabelOverlap: false,
            label: {
              show: true,
              position: 'outside',
              formatter: function (params) {
                return `${params.name}${params.percent}%\n${params.value}(kWh)`
              },
              fontSize: 12,
              fontWeight: 'bold'
            },
            labelLine: {
              show: true,
              length: 15,
              length2: 10,
              smooth: true
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '14',
                fontWeight: 'bold'
              }
            },
            data: [
              {
                value: data.sharpElectricity,
                name: '尖',
                itemStyle: { color: '#ff6b6b' },
                label: {
                  color: '#ff6b6b'
                }
              },
              {
                value: data.peakElectricity,
                name: '峰',
                itemStyle: { color: '#66b1ff' },
                label: {
                  color: '#66b1ff'
                }
              },
              {
                value: data.flatElectricity,
                name: '平',
                itemStyle: { color: '#18f2ce' },
                label: {
                  color: '#18f2ce'
                }
              },
              {
                value: data.valleyElectricity,
                name: '谷',
                itemStyle: { color: '#ffc107' },
                label: {
                  color: '#ffc107'
                }
              }
            ]
          },
          {
            name: '平均电价',
            type: 'pie',
            radius: ['0%', '30%'],
            center: ['50%', '45%'],
            label: {
              show: true,
              position: 'center',
              formatter: () => {
                return `${data.avgPrice}\n平均电价`
              },
              fontSize: 14,
              fontWeight: 'bold'
            },
            labelLine: {
              show: false
            },
            data: [
              {
                value: 1,
                itemStyle: { color: '#008000' }
              }
            ]
          }
        ]
      }
    },

    // 日用电量表格数据
    dailyElectricityTableData() {
      if (!this.reportData || !this.reportData.companyTotalElectricityView) {
        return []
      }

      // 假设API返回的数据结构包含日用电量数据
      // 如果数据结构不同，需要根据实际API调整
      const data = this.reportData.companyTotalElectricityView

      // 过滤掉合计数据，只显示具体日期的数据
      return data.filter((item) => item.dateStr && item.dateStr !== '合计')
    },

    // 日用电量柱状图配置
    dailyElectricityChartOptions() {
      const data = this.dailyElectricityTableData

      if (!data || data.length === 0) {
        return {
          title: {
            text: '日用电量柱状图',
            left: 'center'
          },
          xAxis: {
            type: 'category'
          },
          yAxis: {
            type: 'value',
            name: '电量(kWh)'
          },
          series: []
        }
      }

      // 提取日期和各类电量数据
      const dates = data.map((item) => item.dateStr)
      const sharpData = data.map(
        (item) => parseFloat(item.sharpElectricity) || 0
      )
      const peakData = data.map((item) => parseFloat(item.peakElectricity) || 0)
      const flatData = data.map((item) => parseFloat(item.flatElectricity) || 0)
      const valleyData = data.map(
        (item) => parseFloat(item.valleyElectricity) || 0
      )

      return {
        title: {
          text: '日用电量柱状图',
          left: 'center',
          textStyle: {
            fontSize: 16,
            fontWeight: 'bold'
          }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          top: '15%',
          containLabel: true
        },
        xAxis: {
          type: 'category'
        },
        yAxis: {
          type: 'value',
          name: '电量(kWh)'
        },
        series: [
          {
            name: '尖(kWh)',
            type: 'bar',
            stack: 'total',
            data: sharpData.map((value, index) => [dates[index], value]),
            itemStyle: {
              color: '#ff6b6b'
            }
          },
          {
            name: '峰(kWh)',
            type: 'bar',
            stack: 'total',
            data: peakData.map((value, index) => [dates[index], value]),
            itemStyle: {
              color: '#66b1ff'
            }
          },
          {
            name: '平(kWh)',
            type: 'bar',
            stack: 'total',
            data: flatData.map((value, index) => [dates[index], value]),
            itemStyle: {
              color: '#18f2ce'
            }
          },
          {
            name: '谷(kWh)',
            type: 'bar',
            stack: 'total',
            data: valleyData.map((value, index) => [dates[index], value]),
            itemStyle: {
              color: '#ffc107'
            }
          }
        ]
      }
    },

    // 变压器用电量数据
    transformerElectricityData() {
      if (!this.reportData || !this.reportData.transformerElectricityView) {
        return []
      }

      // 从transformerElectricityView字段获取变压器用电量数据
      const data = this.reportData.transformerElectricityView

      // 如果数据是字符串，尝试解析为JSON
      let transformerData = data
      if (typeof data === 'string') {
        try {
          transformerData = JSON.parse(data)
        } catch (error) {
          console.error('解析transformerElectricityView数据失败:', error)
          return []
        }
      }

      // 确保是数组格式
      if (!Array.isArray(transformerData)) {
        return []
      }

      return transformerData
    },

    // 变压器饼图配置列表
    transformerPieOptionsList() {
      return this.transformerElectricityData.map((transformer, index) => ({
        id: transformer.id || `pie-${index}`,
        name: transformer.name,
        index: index,
        options: this.generateTransformerPieOptions(transformer)
      }))
    },

    // 事件分析数据
    eventAnalysisData() {
      if (!this.reportData || !this.reportData.equipEventListView) {
        return []
      }

      // 从equipEventListView字段获取事件分析数据
      const data = this.reportData.equipEventListView

      // 如果数据是字符串，尝试解析为JSON
      let eventData = data
      if (typeof data === 'string') {
        try {
          eventData = JSON.parse(data)
        } catch (error) {
          console.error('解析equipEventListView数据失败:', error)
          return []
        }
      }

      // 确保是数组格式
      if (!Array.isArray(eventData)) {
        return []
      }

      return eventData
    },

    // 变压器负荷分析数据
    transformerLoadData() {
      if (!this.reportData || !this.reportData.transformerLoadView) {
        return []
      }

      // 从transformerLoadView字段获取变压器负荷分析数据
      const data = this.reportData.transformerLoadView

      // 如果数据是字符串，尝试解析为JSON
      let loadData = data
      if (typeof data === 'string') {
        try {
          loadData = JSON.parse(data)
        } catch (error) {
          console.error('解析transformerLoadView数据失败:', error)
          return []
        }
      }

      // 确保是数组格式
      if (!Array.isArray(loadData)) {
        return []
      }

      return loadData
    },

    // 变压器负荷分析图表配置列表
    transformerLoadChartOptionsList() {
      return this.transformerLoadData.map((transformer, index) => ({
        id: transformer.id || `load-${index}`,
        name:
          transformer.name || transformer.equipmentName || `变压器${index + 1}`,
        index: index,
        options: this.generateTransformerLoadChartOptions(transformer)
      }))
    },

    // 功率因数分析数据
    powerFactorData() {
      if (!this.reportData || !this.reportData.powerFactorView) {
        return []
      }

      // 从powerFactorView字段获取功率因数分析数据
      const data = this.reportData.powerFactorView

      // 如果数据是字符串，尝试解析为JSON
      let factorData = data
      if (typeof data === 'string') {
        try {
          factorData = JSON.parse(data)
        } catch (error) {
          console.error('解析powerFactorView数据失败:', error)
          return []
        }
      }

      // 确保是数组格式
      if (!Array.isArray(factorData)) {
        return []
      }

      return factorData
    },

    // 三相不平衡分析数据
    threePhaseUnbalanceData() {
      if (!this.reportData || !this.reportData.threePhaseImbalanceView) {
        return []
      }
      const data = this.reportData.threePhaseImbalanceView
      let unbalanceData = data
      if (typeof data === 'string') {
        try {
          unbalanceData = JSON.parse(data)
        } catch (error) {
          console.error('解析threePhaseImbalanceView数据失败:', error)
          return []
        }
      }
      if (!Array.isArray(unbalanceData)) {
        return []
      }
      return unbalanceData
    },

    // 电压偏差分析数据
    voltageDeviationData() {
      if (!this.reportData || !this.reportData.voltageDeviationView) {
        return []
      }
      const data = this.reportData.voltageDeviationView
      let deviationData = data
      if (typeof data === 'string') {
        try {
          deviationData = JSON.parse(data)
        } catch (error) {
          console.error('解析voltageDeviationView数据失败:', error)
          return []
        }
      }
      if (!Array.isArray(deviationData)) {
        return []
      }
      return deviationData
    },

    // 谐波分析数据
    harmonicAnalysisData() {
      if (!this.reportData || !this.reportData.harmonicView) {
        return []
      }
      const data = this.reportData.harmonicView
      let harmonicData = data
      if (typeof data === 'string') {
        try {
          harmonicData = JSON.parse(data)
        } catch (error) {
          console.error('解析harmonicView数据失败:', error)
          return []
        }
      }
      if (!Array.isArray(harmonicData)) {
        return []
      }
      return harmonicData
    },

    // 功率因数图表配置
    powerFactorChartOptions() {
      if (!this.reportData || !this.reportData.powerFactorView) {
        return {
          tooltip: { trigger: 'axis' },
          legend: { top: 10, left: 'center' },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            top: '15%',
            containLabel: true
          },
          xAxis: { type: 'category' },
          yAxis: { type: 'value' },
          series: []
        }
      }

      const data = this.reportData.powerFactorView
      let factorData = data
      if (typeof data === 'string') {
        try {
          factorData = JSON.parse(data)
        } catch (error) {
          console.error('解析powerFactorView数据失败:', error)
          return {
            tooltip: { trigger: 'axis' },
            legend: { top: 10, left: 'center' },
            grid: {
              left: '3%',
              right: '4%',
              bottom: '3%',
              top: '15%',
              containLabel: true
            },
            xAxis: { type: 'category' },
            yAxis: { type: 'value' },
            series: []
          }
        }
      }

      // 确保是数组格式
      if (!Array.isArray(factorData)) {
        return {
          tooltip: { trigger: 'axis' },
          legend: { top: 10, left: 'center' },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            top: '15%',
            containLabel: true
          },
          xAxis: { type: 'category' },
          yAxis: { type: 'value' },
          series: []
        }
      }

      // 定义颜色数组
      // 生成series数据
      const seriesData = factorData.map((item, index) => {
        const chartData = item.averagePowerFactorLine || []
        const data = chartData.map((dataItem) => [
          dataItem.timeReading,
          parseFloat(dataItem.valueReading) || 0
        ])

        return {
          name: item.name || `变压器${index + 1}`,
          type: 'line',
          data: data,
          symbol: 'emptyCircle',
          symbolSize: 6
        }
      })

      return {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross'
          }
        },
        legend: {
          top: 10,
          left: 'center'
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          top: '15%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          axisLabel: {
            fontSize: 12
          }
        },
        yAxis: {
          type: 'value',
          name: '功率因数',
          axisLabel: {
            fontSize: 12
          },
          nameTextStyle: {
            fontSize: 12
          }
        },
        series: seriesData
      }
    }
  },
  methods: {
    // 格式化数值显示：0显示为0，null/undefined显示为-
    formatNumber(value) {
      if (value === null || value === undefined) {
        return '-'
      }
      // 如果值为0，显示0
      if (value === 0 || value === '0') {
        return '0'
      }
      return String(value)
    },

    // 获取表头单元格样式
    getHeaderCellStyle() {
      return {
        backgroundColor: '#f5f7fa',
        color: '#606266',
        fontWeight: 'bold',
        textAlign: 'center',
        border: '1px solid #dcdfe6',
        padding: '8px 12px',
        fontSize: '13px'
      }
    },

    // 下载报告
    async downloadReport() {
      try {
        this.downloadLoading = true

        // 获取所有图表的base64数据
        const chartData = await this.getChartsBase64()

        // 调用预存图表数据接口
        await saveElectricRunReportPictureApi({
          id: this.currentRow.id,
          ...chartData
        })

        // 参考ViewReport.vue的下载方式
        const axios = require('axios')

        const res = await axios({
          method: 'POST',
          url: `/biz/pio-microservice-biz/pio/ect/report/form/electric/run/report/download?id=${this.currentRow.id}`,
          responseType: 'blob'
        })

        const blob = new Blob([res.data], { type: 'application/pdf' })
        download(
          blob,
          `配电运行报告_${this.currentRow.orgName}_${this.currentRow.month}.pdf`
        )

        this.$message.success('报告下载成功')
      } catch (error) {
        console.error('下载报告失败:', error)
        this.$message.error('下载报告失败，请重试')
      } finally {
        this.downloadLoading = false
      }
    },

    // 获取所有图表的base64数据
    async getChartsBase64() {
      const chartData = {}

      try {
        // 功率因数分析图
        const powerFactorChart = document.querySelector(
          '#power-factor-chart canvas'
        )
        if (powerFactorChart) {
          chartData.powerFactorAnalysisChart = powerFactorChart.toDataURL()
        }

        // 电价分析曲线图
        const priceChart = document.querySelector(
          '#price-analysis-chart canvas'
        )
        if (priceChart) {
          chartData.priceAnalysisChart = priceChart.toDataURL()
        }

        // 本月负荷特性曲线图
        const loadChart = document.querySelector('#load-chart canvas')
        if (loadChart) {
          chartData.thisMonthLoadChart = loadChart.toDataURL()
        }

        // 企业总用电量柱状图
        const barChart = document.querySelector(
          '#total-electric-bar-chart canvas'
        )
        if (barChart) {
          chartData.totalElectricBarChart = barChart.toDataURL()
        }

        // 企业总用电量饼图
        const pieChart = document.querySelector(
          '#total-electric-pie-chart canvas'
        )
        if (pieChart) {
          chartData.totalElectricPieChart = pieChart.toDataURL()
        }

        // 典型日负荷曲线
        const typicalDayChart = document.querySelector(
          '#typical-day-load-chart canvas'
        )
        if (typicalDayChart) {
          chartData.typicalDayLoadChart = typicalDayChart.toDataURL()
        }

        // 变压器分析图（多个）
        const transformerCharts = document.querySelectorAll(
          '.transformer-load-chart canvas'
        )
        chartData.transformerAnalysisChart = Array.from(transformerCharts).map(
          (canvas) => canvas.toDataURL()
        )

        // 变压器电量结构饼图（多个）
        const transformerPieCharts = document.querySelectorAll(
          '.transformer-pie-chart canvas'
        )
        chartData.transformerElectricPieChart = Array.from(
          transformerPieCharts
        ).map((canvas) => canvas.toDataURL())
      } catch (error) {
        console.error('获取图表base64数据失败:', error)
      }

      return chartData
    },

    // 生成变压器饼图配置
    generateTransformerPieOptions(transformer) {
      const sharpElectricity = parseFloat(transformer.sharpElectricity) || 0
      const peakElectricity = parseFloat(transformer.peakElectricity) || 0
      const flatElectricity = parseFloat(transformer.flatElectricity) || 0
      const valleyElectricity = parseFloat(transformer.valleyElectricity) || 0
      const totalElectricity =
        sharpElectricity + peakElectricity + flatElectricity + valleyElectricity

      // 计算平均电价
      const avgPrice = transformer.averageElectricityPrice || 0

      return {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'horizontal',
          bottom: 0,
          data: ['尖', '峰', '平', '谷']
        },
        series: [
          {
            name: '用电量',
            type: 'pie',
            radius: ['40%', '70%'],
            center: ['50%', '45%'],
            avoidLabelOverlap: false,
            label: {
              show: true,
              position: 'outside',
              formatter: function (params) {
                return `${params.name}${params.percent}%\n${params.value}(kWh)`
              },
              fontSize: 12,
              fontWeight: 'bold'
            },
            labelLine: {
              show: true,
              length: 15,
              length2: 10,
              smooth: true
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '14',
                fontWeight: 'bold'
              }
            },
            data: [
              {
                value: sharpElectricity,
                name: '尖',
                itemStyle: { color: '#ff6b6b' },
                label: {
                  color: '#ff6b6b'
                }
              },
              {
                value: peakElectricity,
                name: '峰',
                itemStyle: { color: '#66b1ff' },
                label: {
                  color: '#66b1ff'
                }
              },
              {
                value: flatElectricity,
                name: '平',
                itemStyle: { color: '#18f2ce' },
                label: {
                  color: '#18f2ce'
                }
              },
              {
                value: valleyElectricity,
                name: '谷',
                itemStyle: { color: '#ffc107' },
                label: {
                  color: '#ffc107'
                }
              }
            ]
          },
          {
            name: '平均电价',
            type: 'pie',
            radius: ['0%', '30%'],
            center: ['50%', '45%'],
            label: {
              show: true,
              position: 'center',
              formatter: () => {
                return `${avgPrice}\n平均电价`
              },
              fontSize: 14,
              fontWeight: 'bold'
            },
            labelLine: {
              show: false
            },
            data: [
              {
                value: 1,
                itemStyle: { color: '#008000' }
              }
            ]
          }
        ]
      }
    },

    // 生成markArea时段数据
    generateMarkAreaSegments(timeList, segmentName, color) {
      if (!timeList || timeList.length === 0) {
        return []
      }

      // 过滤空字符串并转换为时间格式
      const formattedTimes = timeList
        .filter((time) => time && time.trim() !== '')
        .map((time) => {
          const hour = time.substring(0, 2)
          const minute = time.substring(2, 4)
          return `${hour}:${minute}`
        })

      if (formattedTimes.length === 0) {
        return []
      }

      // 按时间排序
      formattedTimes.sort()

      const segments = []
      let currentStart = formattedTimes[0]
      let currentEnd = formattedTimes[0]

      for (let i = 1; i < formattedTimes.length; i++) {
        const prevTime = formattedTimes[i - 1]
        const currentTime = formattedTimes[i]

        // 计算时间差（分钟）
        const [prevHour, prevMinute] = prevTime.split(':').map(Number)
        const [currentHour, currentMinute] = currentTime.split(':').map(Number)
        const prevTotalMinutes = prevHour * 60 + prevMinute
        const currentTotalMinutes = currentHour * 60 + currentMinute

        // 如果时间差小于等于15分钟，认为是连续时段
        if (currentTotalMinutes - prevTotalMinutes <= 15) {
          currentEnd = currentTime
        } else {
          // 结束当前时段，开始新时段
          // 不添加额外时间，避免重叠
          segments.push([
            {
              name: segmentName,
              xAxis: currentStart,
              itemStyle: {
                color: color,
                opacity: 0.4
              }
            },
            {
              xAxis: currentEnd,
              itemStyle: {
                color: color,
                opacity: 0.4
              }
            }
          ])
          currentStart = currentTime
          currentEnd = currentTime
        }
      }

      // 添加最后一个时段，不添加额外时间
      segments.push([
        {
          name: segmentName,
          xAxis: currentStart,
          itemStyle: {
            color: color,
            opacity: 0.4
          }
        },
        {
          xAxis: currentEnd,
          itemStyle: {
            color: color,
            opacity: 0.4
          }
        }
      ])

      return segments
    },

    // 基于接口四类时段，生成全天连续不重叠的 markArea
    generateUnifiedMarkAreas(priceData) {
      // 颜色映射
      const segmentColorMap = {
        尖: '#ff6b6b',
        峰: '#66b1ff',
        平: '#67c23a',
        谷: '#ffc107'
      }

      // 将 HHMM 转换为 HH:MM 格式
      const formatTime = (hhmm) => {
        if (!hhmm || String(hhmm).trim() === '') return null
        const time = String(hhmm).padStart(4, '0')
        return `${time.substring(0, 2)}:${time.substring(2, 4)}`
      }

      // 将时间列表转换为连续区间
      const createSegments = (timeList, type) => {
        if (!Array.isArray(timeList) || timeList.length === 0) return []

        // 过滤并格式化时间
        const validTimes = timeList
          .filter((t) => t && String(t).trim() !== '')
          .map((t) => formatTime(t))
          .filter((t) => t !== null)
          .sort()

        if (validTimes.length === 0) return []

        const segments = []
        let currentStart = validTimes[0]
        let currentEnd = validTimes[0]

        // 减去15分钟到时间的辅助函数
        const subtractMinutes = (timeStr, minutes) => {
          const [hour, minute] = timeStr.split(':').map(Number)
          const totalMinutes = hour * 60 + minute - minutes
          if (totalMinutes < 0) return '00:00' // 如果小于0，返回00:00
          const newHour = Math.floor(totalMinutes / 60) % 24
          const newMinute = totalMinutes % 60
          return `${newHour.toString().padStart(2, '0')}:${newMinute
            .toString()
            .padStart(2, '0')}`
        }

        for (let i = 1; i < validTimes.length; i++) {
          const current = validTimes[i]
          const prev = validTimes[i - 1]

          // 计算时间差（分钟）
          const getMinutes = (time) => {
            const [hours, minutes] = time.split(':').map(Number)
            return hours * 60 + minutes
          }

          const currentMinutes = getMinutes(current)
          const prevMinutes = getMinutes(prev)

          // 如果时间间隔是15分钟，继续当前区间
          if (currentMinutes - prevMinutes === 15) {
            currentEnd = current
          } else {
            // 结束当前区间，开始新区间
            // 如果开始时间不是00:00，则减去15分钟
            const startTime =
              currentStart === '00:00'
                ? currentStart
                : subtractMinutes(currentStart, 15)
            segments.push([
              {
                name: type,
                xAxis: startTime,
                itemStyle: {
                  color: segmentColorMap[type],
                  opacity: 0.35
                }
              },
              {
                xAxis: currentEnd
              }
            ])
            currentStart = current
            currentEnd = current
          }
        }

        // 添加最后一个区间
        // 如果开始时间不是00:00，则减去15分钟
        const startTime =
          currentStart === '00:00'
            ? currentStart
            : subtractMinutes(currentStart, 15)
        segments.push([
          {
            name: type,
            xAxis: startTime,
            itemStyle: {
              color: segmentColorMap[type],
              opacity: 0.35
            }
          },
          {
            xAxis: currentEnd
          }
        ])

        return segments
      }

      // 生成各时段的区间
      const sharpSegments = createSegments(priceData.sharpTimeList, '尖')
      const peakSegments = createSegments(priceData.peakTimeList, '峰')
      const flatSegments = createSegments(priceData.flatTimeList, '平')
      const valleySegments = createSegments(priceData.valleyTimeList, '谷')

      // 合并所有区间
      return [
        ...sharpSegments,
        ...peakSegments,
        ...flatSegments,
        ...valleySegments
      ]
    },

    // 设置默认日期范围（当年1月到本月）
    setDefaultDateRange() {
      const currentYear = new Date().getFullYear()
      const currentMonth = new Date().getMonth() + 1
      const startMonth = `${currentYear}-01`
      const endMonth = `${currentYear}-${currentMonth
        .toString()
        .padStart(2, '0')}`

      this.dateRange = [startMonth, endMonth]
      this.form.startMonth = startMonth
      this.form.endMonth = endMonth
    },
    // 获取用电企业列表
    async getCompanyList() {
      try {
        const res = await getCompanyListApi()
        this.companyList = res.data.list || []
        if (this.companyList.length > 0) {
          // 使用 bizOrgNo 字段（企业编码）
          this.form.orgNo = this.companyList[0].bizOrgNo
        }
      } catch (error) {
        console.error('获取企业列表失败:', error)
        this.$message.error('获取企业列表失败')
      }
    },
    // 企业选择变化
    companyChange(value) {
      // 根据选中的企业查找对应的 bizOrgNo
      const selectedCompany = this.companyList.find((c) => c.bizOrgNo === value)
      if (selectedCompany) {
        this.form.orgNo = selectedCompany.bizOrgNo
      }
    },
    // 日期范围变化
    dateRangeChange(dateRange) {
      if (dateRange && dateRange.length === 2) {
        this.form.startMonth = dateRange[0]
        this.form.endMonth = dateRange[1]
      } else {
        this.form.startMonth = ''
        this.form.endMonth = ''
      }
    },
    // 获取数据
    async getdatalist() {
      this.loading = true
      try {
        // 调用真实接口
        const params = {
          orgNo: this.form.orgNo,
          startMonth: this.form.startMonth,
          endMonth: this.form.endMonth
        }

        const res = await getElectricRunReportListApi(params)

        if (res.code === 200 && res.data) {
          // 直接使用接口返回的数据
          this.tableData = res.data.list || []
          this.total = res.data.totalCount || this.tableData.length
        } else {
          this.$message.error(res.message || '获取数据失败')
          this.tableData = []
          this.total = 0
        }
      } catch (error) {
        console.error('获取数据失败:', error)
        this.$message.error('获取数据失败')
        this.tableData = []
        this.total = 0
      } finally {
        this.loading = false
      }
    },
    // 分页查询
    currentChange() {
      this.getdatalist()
    },
    // 查询
    chaxun() {
      this.pageobj._pageNo = 1
      this.getdatalist()
    },
    // 重置
    async chongzhi() {
      // 重置为第一个企业的 bizOrgNo
      if (this.companyList.length > 0) {
        this.form.orgNo = this.companyList[0].bizOrgNo
      } else {
        this.form.orgNo = ''
      }
      this.setDefaultDateRange()
      this.pageobj._pageNo = 1
      await this.getdatalist()
    },
    // 刷新列表
    shuaxin() {
      this.getdatalist()
      this.$message({
        type: 'success',
        message: '列表刷新成功',
        duration: 2000
      })
    },
    // 导出
    daochu() {
      const params = {
        orgNo: this.form.orgNo,
        startMonth: this.form.startMonth,
        endMonth: this.form.endMonth
      }

      exportexcel(
        '/pio-microservice-biz/pio/ect/report/form/electric/run/report/exportExcel',
        params,
        '配电运行报告'
      )
    },
    // 表格密度
    command(val) {
      if (val === '默认') {
        this.iissize = 'medium'
      } else if (val === '中等') {
        this.iissize = 'small'
      } else {
        this.iissize = 'mini'
      }
    },
    // 打开报告对话框
    async openReportDialog(row, type) {
      this.currentRow = { ...row }
      this.generateForm.remark = ''

      if (type === 'view') {
        // 浏览报告：调用浏览接口
        this.loading = true
        try {
          const res = await viewElectricRunReportApi(row.id)

          if (res.code === 200) {
            // 保存报告数据
            this.reportData = res.data.entity
            this.generateDialogVisible = true
          } else {
            this.$message.error(res.message || '报告加载失败')
          }
        } catch (error) {
          console.error('浏览报告失败:', error)
          this.$message.error('报告加载失败，请稍后重试')
        } finally {
          this.loading = false
        }
      }
    },

    // 关闭对话框
    closeDialog() {
      this.generateDialogVisible = false
    },
    // 确认生成报告
    confirmGenerate() {
      this.$message.success('报告生成成功（模拟）')
      this.generateDialogVisible = false
      this.getdatalist()
    },
    // 生成单个报告
    async generateSingleReport(row) {
      this.$confirm(
        `确定要为 ${row.companyName} 的 ${row.yearMonth} 生成报告吗？`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(async () => {
        try {
          const res = await generateMaintenanceReportApi({
            companyId: row.companyId,
            yearMonth: row.yearMonth
          })
          if (res.code === 200) {
            this.$message.success('报告生成成功')
            this.getdatalist()
          } else {
            this.$message.error(res.message || '报告生成失败')
          }
        } catch (error) {
          console.error('生成报告失败:', error)
          // 模拟生成成功
          this.$message.success('报告生成成功（模拟）')
          this.getdatalist()
        }
      })
    },
    // 浏览报告
    viewReport(row) {
      // 这里可以打开报告预览弹窗或跳转到报告详情页
      this.$message.info('浏览报告功能待实现')
    },
    // 生成报告
    async generateReport(row) {
      this.loading = true
      try {
        const params = {
          orgNo: row.orgNo,
          month: row.month
        }

        const res = await generateElectricRunReportApi(params)

        if (res.code === 200) {
          this.$message.success('报告生成成功')
          // 刷新列表
          await this.getdatalist()
        } else {
          this.$message.error(res.message || '报告生成失败')
        }
      } catch (error) {
        console.error('生成报告失败:', error)
        this.$message.error('生成报告失败，请稍后重试')
      } finally {
        this.loading = false
      }
    },
    // 删除报告
    async handleDel(row) {
      this.loading = true
      try {
        const res = await deleteElectricRunReportApi(row.id)
        if (res.code === 200) {
          this.$message.success('删除成功')
          // 如果删除后当前页没有数据，跳转到上一页
          if (this.tableData.length === 1 && this.pageobj._pageNo > 1) {
            this.pageobj._pageNo--
          }
          await this.getdatalist()
        } else {
          this.$message.error(res.message || '删除失败')
        }
      } catch (error) {
        console.error('删除失败:', error)
        this.$message.error('删除失败，请稍后重试')
      } finally {
        this.loading = false
      }
    },

    // 生成变压器负荷分析图表配置
    generateTransformerLoadChartOptions(transformer) {
      // 检查是否有loadCurve数据
      if (
        !transformer.loadCurve ||
        !Array.isArray(transformer.loadCurve) ||
        transformer.loadCurve.length === 0
      ) {
        return {
          tooltip: {
            trigger: 'axis'
          },
          legend: {
            top: 10,
            left: 'center'
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            top: '15%',
            containLabel: true
          },
          xAxis: {
            type: 'category'
          },
          yAxis: [
            {
              type: 'value',
              name: '负荷(kW)',
              position: 'left'
            },
            {
              type: 'value',
              name: '负载率(%)',
              position: 'right'
            }
          ],
          series: []
        }
      }
      const seriesData = transformer.loadCurve.map((curve) => {
        const data =
          curve.datalist && Array.isArray(curve.datalist)
            ? curve.datalist.map((item) => {
                return [item.timeReading, item.valueReading]
              })
            : []

        return {
          name: curve.name,
          type: curve.name === '最大负荷' ? 'bar' : 'line',
          data: data,
          yAxisIndex: curve.name === '最大负荷' ? 0 : 1,
          itemStyle: {
            color: curve.name === '最大负荷' ? '#5470c6' : '#91cc75'
          },
          ...(curve.name === '平均负载率'
            ? {
                lineStyle: {
                  color: '#91cc75'
                },
                symbol: 'circle',
                symbolSize: 6,
                itemStyle: {
                  color: '#91cc75',
                  borderColor: '#91cc75',
                  borderWidth: 2
                },
                emphasis: {
                  itemStyle: {
                    color: '#91cc75',
                    borderColor: '#91cc75',
                    borderWidth: 2
                  }
                }
              }
            : {})
        }
      })

      return {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: {
          top: 10,
          left: 'center'
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          top: '15%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          axisLabel: {
            fontSize: 12
          }
        },
        yAxis: [
          {
            type: 'value',
            name: '负荷(kW)',
            position: 'left',
            axisLabel: {
              fontSize: 12
            },
            nameTextStyle: {
              fontSize: 12
            }
          },
          {
            type: 'value',
            name: '负载率(%)',
            position: 'right',
            axisLabel: {
              fontSize: 12
            },
            nameTextStyle: {
              fontSize: 12
            }
          }
        ],
        series: seriesData
      }
    }
    // 检查文本是否溢出
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-select {
  width: 100%;
}
.option {
  height: auto;
}
.bigbox {
  background-color: #f1f1f1;
  padding: 10px;
  height: 100%;
  .topbox {
    background-color: #fff;
    padding: 20px;
    box-sizing: border-box;
    height: 80px !important;
    width: 100% !important;
  }
  .bodybox {
    background-color: #fff;
    margin-top: 10px;
    padding: 20px 20px 20px 20px;
    height: 90%;
    .titlebox {
      display: flex;
      justify-content: space-between;
      margin-bottom: 10px;
      .text {
        font-weight: bold;
        font-size: 18px;
      }
      .right {
        align-items: center;
        i {
          margin-left: 10px;
        }
      }
    }
    .fenye {
      margin-top: 15px;
      text-align: right;
    }
  }
}

.operate {
  display: flex;
  justify-content: space-around;
  align-items: center;
}

.report-content {
  p {
    line-height: 2;
    font-size: 14px;
    margin: 10px 0;
  }
}

::v-deep .el-dialog__body {
  overflow-y: auto;
  // max-height: 80vh;
}

.project-overview-table {
  @extend .base-table;

  td {
    padding: 12px 16px;
    font-size: 14px;
  }

  .table-label {
    @extend .table-header;
    width: 120px;
  }

  .table-value {
    @extend .table-data;
    width: 140px;
  }

  .table-empty {
    background-color: #fff;
    width: 120px;
  }
}

.transformer-info-table {
  @extend .base-table;

  td {
    padding: 12px 16px;
    font-size: 14px;
  }
}

.electricity-basic-table {
  @extend .base-table;

  /* 调整列宽 */
  th:nth-child(1),
  td:nth-child(1) {
    width: 80px; /* 序号列 */
    min-width: 80px;
  }

  th:nth-child(6),
  td:nth-child(6) {
    width: 100px; /* 评价列 */
    min-width: 100px;
  }
}

.table-container {
  overflow-x: auto; /* 水平滚动 */
  margin-bottom: 20px;
  max-width: 100%;
}

/* 3.4 企业总用电量 */
.power-cards-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr); /* Two columns */
  gap: 15px; /* Gap between cards */
  flex: 1; /* Takes up available space */
  max-width: 50%; /* Limit width to roughly half for cards */
  min-width: 300px; /* Ensure it doesn't get too small */
  padding-right: 15px; /* Space between cards grid and pie chart */
}

.power-card {
  display: flex;
  align-items: center;
  padding: 15px;
  border-radius: 8px;
  color: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  min-height: 80px; /* Ensure consistent height */
  justify-content: space-between;
}

.power-card .card-icon {
  font-size: 36px; /* Larger icon */
  margin-right: 15px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.power-card .card-left {
  display: flex;
  align-items: center;
  flex-grow: 1;
}

.power-card .card-title {
  font-size: 16px;
  font-weight: bold;
  margin-left: 15px;
  opacity: 0.9;
}

.power-card .card-value-percentage {
  font-size: 16px;
  font-weight: bold;
  text-align: right;
  line-height: 1.2;
}

/* Card Colors */
.red-card {
  background-color: #ff6b6b;
}
.blue-card {
  background-color: #66b1ff;
}
.green-card {
  background-color: #18f2ce;
}
.orange-card {
  background-color: #ffc107;
}

/* Pie Chart Section */
.power-pie-chart-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  position: relative;
  min-width: 350px;
  height: 300px;
}

.pie-chart-wrapper {
  width: 200px;
  height: 200px;
  border-radius: 50%;
  background: conic-gradient(
    #ff6b6b 0% 24.39%,
    #66b1ff 24.39% 63.32%,
    #67c23a 63.32% 63.32%,
    #ffc107 63.32% 100%
  );
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 15px;
  box-shadow: 0 0 0 1px #e0e0e0;
}

.pie-chart-center-content {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  background-color: white;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  box-shadow: 0 0 0 1px #e0e0e0;
}

.average-price-value {
  font-size: 24px;
  font-weight: bold;
  color: #67c23a;
}

.average-price-label {
  font-size: 12px;
  color: #606266;
}

/* Pie Chart Labels */
.pie-label {
  position: absolute;
  font-size: 12px;
  color: #303133;
  white-space: nowrap;
  line-height: 1.3;
  text-align: center;
  z-index: 10;
}

.pie-label .label-text {
  display: inline-block;
  padding: 4px 8px;
  background-color: rgba(255, 255, 255, 0.9);
  border-radius: 4px;
  border: 1px solid #e0e0e0;
}

.pie-label .label-line {
  position: absolute;
  background-color: #909399;
  height: 1px;
  width: 20px;
  z-index: -1;
}

/* Specific label positioning and line adjustments */
.pie-chart-wrapper .red-label {
  top: -20px;
  right: -100px;
  text-align: left;
}
.pie-chart-wrapper .red-label .label-line {
  width: 80px;
  left: -80px;
  top: 20px;
  transform: rotate(-30deg);
  transform-origin: right center;
}

.pie-chart-wrapper .blue-label {
  bottom: -20px;
  right: -100px;
  text-align: left;
}
.pie-chart-wrapper .blue-label .label-line {
  width: 80px;
  left: -80px;
  top: 20px;
  transform: rotate(30deg);
  transform-origin: right center;
}

.pie-chart-wrapper .green-label {
  bottom: -20px;
  left: -100px;
  text-align: right;
}
.pie-chart-wrapper .green-label .label-line {
  width: 80px;
  right: -80px;
  top: 20px;
  transform: rotate(-30deg);
  transform-origin: left center;
}

.pie-chart-wrapper .orange-label {
  top: -20px;
  left: -100px;
  text-align: right;
}
.pie-chart-wrapper .orange-label .label-line {
  width: 80px;
  right: -80px;
  top: 20px;
  transform: rotate(30deg);
  transform-origin: left center;
}

/* Pie Chart Legend */
.pie-legend {
  display: flex;
  justify-content: center;
  gap: 15px;
  margin-top: 10px;
  font-size: 13px;
  color: #606266;
}

.legend-item {
  display: flex;
  align-items: center;
}

.color-box {
  width: 12px;
  height: 12px;
  border-radius: 2px;
  margin-right: 5px;
  display: inline-block;
}

.color-box.red {
  background-color: #ff6b6b;
}
.color-box.blue {
  background-color: #66b1ff;
}
.color-box.green {
  background-color: #67c23a;
}
.color-box.orange {
  background-color: #ffc107;
}

/* 3.5 变压器用电量 */
.transformer-summary-table {
  @extend .base-table;
}

.transformer-charts-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20px;
  margin-top: 20px;
}

.transformer-chart-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 15px;
  background-color: #fff;
  border: none;
  border-radius: 0;
  box-shadow: none;
  position: relative;
  padding-top: 40px; /* 为左上角标题留出空间 */
}

.chart-title {
  font-size: 14px;
  font-weight: bold;
  margin-bottom: 15px;
  color: #303133;
  text-align: center;
}

.chart-title-left {
  font-size: 14px;
  font-weight: bold;
  color: #303133;
  text-align: left;
  position: absolute;
  top: 0;
  left: 0;
  z-index: 10;
}

.transformer-donut-chart {
  width: 180px;
  height: 180px;
  border-radius: 50%;
  background: conic-gradient(
    #ff6b6b 0% 33.86%,
    #66b1ff 33.86% 58.04%,
    #67c23a 58.04% 58.04%,
    #ffc107 58.04% 100%
  );
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 15px;
  box-shadow: 0 0 0 1px #e0e0e0;
}

.donut-center {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  background-color: #2d5a27;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  box-shadow: 0 0 0 1px #e0e0e0;
}

.donut-center-value {
  font-size: 20px;
  font-weight: bold;
  color: white;
}

.donut-center-label {
  font-size: 10px;
  color: white;
  opacity: 0.9;
}

/* Transformer Donut Chart Labels */
.transformer-donut-chart .donut-label {
  position: absolute;
  font-size: 10px;
  color: #303133;
  white-space: nowrap;
  line-height: 1.2;
  text-align: center;
  z-index: 10;
}

.transformer-donut-chart .donut-label .label-text {
  display: inline-block;
  padding: 3px 6px;
  background-color: rgba(255, 255, 255, 0.9);
  border-radius: 3px;
  border: 1px solid #e0e0e0;
  font-size: 9px;
}

.transformer-donut-chart .donut-label .label-line {
  position: absolute;
  background-color: #909399;
  height: 1px;
  width: 15px;
  z-index: -1;
}

/* Specific positioning for transformer donut labels */
.transformer-donut-chart .red-label {
  top: -15px;
  right: -70px;
  text-align: left;
}
.transformer-donut-chart .red-label .label-line {
  width: 60px;
  left: -60px;
  top: 15px;
  transform: rotate(-25deg);
  transform-origin: right center;
}

.transformer-donut-chart .blue-label {
  bottom: -15px;
  right: -70px;
  text-align: left;
}
.transformer-donut-chart .blue-label .label-line {
  width: 60px;
  left: -60px;
  top: 15px;
  transform: rotate(25deg);
  transform-origin: right center;
}

.transformer-donut-chart .green-label {
  bottom: -15px;
  left: -70px;
  text-align: right;
}
.transformer-donut-chart .green-label .label-line {
  width: 60px;
  right: -60px;
  top: 15px;
  transform: rotate(-25deg);
  transform-origin: left center;
}

.transformer-donut-chart .orange-label {
  top: -15px;
  left: -70px;
  text-align: right;
}
.transformer-donut-chart .orange-label .label-line {
  width: 60px;
  right: -60px;
  top: 15px;
  transform: rotate(25deg);
  transform-origin: left center;
}

/* Transformer Donut Chart Legend */
.transformer-donut-chart + .donut-legend {
  display: flex;
  justify-content: center;
  gap: 12px;
  margin-top: 10px;
  font-size: 11px;
  color: #606266;
}

.transformer-chart-item .donut-legend {
  display: flex;
  justify-content: center;
  gap: 12px;
  margin-top: 10px;
  font-size: 11px;
  color: #606266;
}

.transformer-chart-item .legend-item {
  display: flex;
  align-items: center;
}

.transformer-chart-item .color-box {
  width: 10px;
  height: 10px;
  border-radius: 2px;
  margin-right: 4px;
  display: inline-block;
}

/* 四、用电安全分析 */
.event-analysis-table {
  @extend .base-table;

  /* 设备列左对齐 */
  td:nth-child(2) {
    text-align: left;
  }
}

/* 五、变压器分析 */
.transformer-load-table {
  @extend .base-table;

  /* 设备列左对齐 */
  td:nth-child(2) {
    text-align: left;
  }
}

.transformer-load-charts {
  display: flex;
  gap: 20px;
  margin-top: 20px;
}

.load-chart-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.load-chart-item .chart-title {
  font-size: 14px;
  font-weight: bold;
  margin-bottom: 15px;
  color: #303133;
  text-align: center;
}

/* 垂直布局的变压器图表 */
.transformer-load-charts-vertical {
  display: flex;
  flex-direction: column;
  gap: 30px;
  margin-top: 20px;
}

.load-chart-item-vertical {
  position: relative;
}

.load-chart-item-vertical .chart-title-left {
  font-size: 14px;
  font-weight: bold;
  color: #303133;
  text-align: left;
  position: absolute;
  top: 0;
  left: 0;
  z-index: 10;
}

/* 六、电能质量分析 */
.power-factor-table {
  @extend .base-table;

  /* 设备列左对齐 */
  td:nth-child(2) {
    text-align: left;
  }
}

/* 三相不平衡分析表格 */
.three-phase-unbalance-table {
  @extend .base-table;

  /* 设备列左对齐 */
  td:nth-child(2) {
    text-align: left;
  }
}

/* 电压偏差分析表格 */
.voltage-deviation-table {
  @extend .base-table;

  /* 设备列左对齐 */
  td:nth-child(2) {
    text-align: left;
  }
}

/* 谐波分析表格 */
.harmonic-analysis-table {
  @extend .base-table;

  /* 设备列左对齐 */
  td:nth-child(2) {
    text-align: left;
  }
}

/* 响应式调整 */
@media (max-width: 768px) {
  .transformer-load-charts {
    flex-direction: column;
  }
}

/* Responsive adjustments */
@media (max-width: 768px) {
  .power-cards-grid {
    max-width: 100%;
    padding-right: 0;
    margin-bottom: 20px;
  }
  .power-pie-chart-section {
    min-width: unset;
    width: 100%;
  }
  .power-pie-chart-section .pie-chart-wrapper {
    width: 180px;
    height: 180px;
  }
  .power-pie-chart-section .pie-chart-center-content {
    width: 100px;
    height: 100px;
  }
  .pie-label {
    font-size: 11px;
  }
  .pie-chart-wrapper .red-label,
  .pie-chart-wrapper .blue-label,
  .pie-chart-wrapper .green-label,
  .pie-chart-wrapper .orange-label {
    right: -80px;
    left: -80px;
  }
  .pie-chart-wrapper .red-label .label-line,
  .pie-chart-wrapper .blue-label .label-line,
  .pie-chart-wrapper .green-label .label-line,
  .pie-chart-wrapper .orange-label .label-line {
    width: 60px;
    left: -60px;
    right: -60px;
  }

  /* Transformer charts responsive */
  .transformer-charts-grid {
    grid-template-columns: 1fr;
  }
  .transformer-donut-chart {
    width: 160px;
    height: 160px;
  }
  .donut-center {
    width: 90px;
    height: 90px;
  }
  .transformer-donut-chart .donut-label {
    font-size: 9px;
  }
  .transformer-donut-chart .red-label,
  .transformer-donut-chart .blue-label,
  .transformer-donut-chart .green-label,
  .transformer-donut-chart .orange-label {
    right: -60px;
    left: -60px;
  }
}

.electricity-cost-table {
  @extend .base-table;
  table-layout: fixed; /* 固定表格布局，防止超出容器 */

  th,
  td {
    word-break: keep-all; /* 保持单词完整性，优先在括号处断行 */
    overflow-wrap: break-word; /* 在必要时强制换行 */
    line-height: 1.4; /* 增加行高以便多行显示 */
    position: relative;
    max-width: 0; /* 配合table-layout: fixed使用 */
  }

  .table-header {
    background-color: #f5f7fa;
    font-weight: bold;
    text-align: center !important;
    color: #606266;
    word-break: keep-all; /* 保持表头单词完整性 */
    vertical-align: middle;
  }

  .table-data {
    background-color: #fff;
    color: #303133;
    text-align: center;
  }

  th:nth-child(2),
  td:nth-child(2) {
    width: 12%; /* 计量点名称 */
    text-align: left;
    padding-left: 8px;
  }

  /* 确保所有其他列都居中 */
  th:not(:nth-child(2)),
  td:not(:nth-child(2)) {
    text-align: center;
  }
}

.electricity-detail-table {
  @extend .base-table;

  tbody tr:nth-child(even) {
    background-color: #fafafa;
  }
}

/* 固定表头和滚动内容区域的样式 */
.electricity-detail-table thead th {
  width: 11.11%; /* 9列平均分配 */
}

.electricity-detail-table tbody td {
  width: 11.11%; /* 9列平均分配 */
}

.electricity-detail-table tbody tr:hover {
  background-color: #f0f9ff;
}

.load-analysis-table {
  @extend .base-table;
}

/* 基础表格样式 */
.base-table {
  width: 100%;
  border-collapse: collapse;
  border: 1px solid #dcdfe6;
  margin-bottom: 20px;
}

.base-table th,
.base-table td {
  padding: 8px 12px;
  border: 1px solid #dcdfe6;
  vertical-align: middle;
  font-size: 13px;
  text-align: center;
}

.base-table tbody tr:nth-child(even) {
  background-color: #fafafa;
}

.base-table tbody tr:hover {
  background-color: #f0f9ff;
}

/* 统一表格样式 */
.table-header {
  background-color: #f5f7fa;
  font-weight: bold;
  text-align: center;
  color: #606266;
}

.table-data {
  background-color: #fff;
  color: #303133;
  text-align: center;
}

.table-note {
  background-color: #fff;
  color: #303133;
  text-align: left;
  font-style: normal;
}

.status-tag {
  background-color: #67c23a;
  color: #fff;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: bold;
}
</style>
